phpclassmagic-function

php without __get function, you can't get a value from certain instances?


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.


Solution

  • 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');