Pergunta

Since my tech book told me so, I'm wondering if that's true, for example:

class A {
    public $attr = "hmm";
}

$a = new A();
echo $a->attr; // outputs hmm

well that works for me, the book says not in order to use it outside class it's not making a __get function. i'm confused a bit.

Foi útil?

Solução 2

Both public variables and magical __get() methods are considered to be a bad practice. First ones cause objects to loose the data encapsulations, while magic getters/setters attract complexity.

It is common to performs some operations on the data in the setter, before it is assigned to a parameter. For example, you would validate email address. Or format of phone number. When instead you use magical __get and __set methods, you will have to do all of this in a single method.

Essentially, your magical setter turns in a huge cluster*uck of if .. else statements of various depth.

Instead you should make a custom getter for instance's parameter that you want to manipulate:

class Book
{
    private $title;
    private $author;

    public function __construct( $author = null, $author = null )
    {
        $this->title = $title;
        $this->author = $author;
    }

    public function setTitle( $title)
    {
        $this->title = $title;
    }

    public function setAuthor( $author)
    {
        $this->author = $author;
    }

}

Which is used as:

$instance = new Book('Jim Butcher');
$isntance->setTitle('Fool Moon');

Outras dicas

Here is an example of using that magic method __get:

class User {
  private $data = array(
    "name" => "Joe",
    "age"  => "10",
    "phrase" => "Hell Yeah"
  ) ;

  public function __get($name){
    return (isset($this->data[$name)) ? $this->data[$name] : null ;
  }
}

$user = new User() ;

echo $user->age ; //Access the property.

$user->age = 5 ; //Will not be possible, does not exist. But you can define __set

Why is it good: It provides so called read only properties. For example object mysqli_result has that stuff. ($result->num_rows) Properties can be easily accessed like that and at the same time cannot be rewritten. Also you can log anything when accessing properties.

Why is it bad: Heavily slows performance because of checks whether the property exists or not and then calling that method if it does not.

__get is a magic function which will be called when your trying to access none-existing properties. first you need to define a __get method in your class

 class foo {

      private $_map = array();

      public function __get($key) {
            if (isset($this->_map[$key])) return $this->_map[$key];
            return null;
      }
 }

then to use this if you do the following code and if you have already populated $_map you can access the values

   $a = new foo();
   $a->bar; //will call __get and pass bar as $key
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top