Question

I don't like having hundreds of naive Setters and Getters but I like to be able to have Setters and Getters for some of the data, since I might have to sanitize them etc.

I've got two ideas how to do this:

class Test {
  private $value = "Value received from: ";
  private $value2 = "Value2 received from: ";

  function __get($property) {
    if (method_exists($this, "get".$property)) {
      return $this->getValue();
    }

    return $this->$property."__get()";
  }

  public function getValue() {
    return $this->value."getValue()";
  }
}

$obj = new Test();
echo $obj->value; // Returns: Value received from: getValue()
echo $obj->value2; // Returns: Value2 received from: __get()

And

class Test {
  private $value = "Value received from: ";
  private $value2 = "Value2 received from: ";

  public function __call($method, $args) {
    if (substr($method, 0, 3) == "get") {
      // Sanitizing so no functions should get through
      $property = preg_replace("/[^0-9a-zA-Z]/", "", strtolower(substr($method, 3)));

      if (isset($this->$property)) {
        return $this->$property."__call";
      }
    }
  }

  public function getValue() {
    return $this->value."getValue()";
  }
}

$obj = new Test();
echo $obj->getValue(); // Returns: Value received from: getValue()
echo $obj->getValue2(); // Returns: Value2 received from: __call

Basically the only difference is between magic method __call and __get. I left out __set because it's pretty obvious how I would do it.

The real question is which one is better? Performance? Readability? Security?

Was it helpful?

Solution

According to the PHP Manual: Overloading, the magic method __get() is for overloading properties, while __call() is for methods. Since you are working with methods, you should use the one appropriate for its designed use. So for Readability, __call() gets my vote.

As far as Security, I think any overloading is just about as equally secure, which is to say not really much at all, since it's about creating properties and methods that haven't been explicitly declared.

I haven't tested the Performance aspect of it. I would think the method __call() would be better as it was designed for use with methods, but you may want to microtime(true) a couple tests to see if it matters.

I honestly don't use __call() since I haven't had the need to overload methods in my apps, or otherwise should say that I always declare methods in my object classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top