Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic methods (__get, __set) not working in extended class? [duplicate]

Tags:

php

<?php 

abstract class AbstractClass
{
    public function __get($theName)
    {
        return (isset($this->$theName)) ? $this->$theName : NULL;
    }

    public function __set($theName, $theValue)
    {
        if (false === property_exists(get_class(), $theName)) {
            throw new Exception(get_class()." does not have '".$theName."' property.");
        } else {
            $this->$theName = $theValue;
        }
    }
}

class ConcreteClass extends AbstractClass
{
        private $x;
        private $y;

        public function __construct($theX, $theY)
        {
            $this->x = $theX;
            $this->y = $theY;
        }
}

$concreteClass = new ConcreteClass(10, 20);

var_dump( $concreteClass->x );

Is there some way to amke this work or will I have to add those magic methods to the extended class?

like image 331
Richard Knop Avatar asked Dec 10 '22 09:12

Richard Knop


1 Answers

This would work:

public function __get($theName)
{
    if(property_exists($this, $theName)) {
        $reflection = new ReflectionProperty($this, $theName);
        $reflection->setAccessible($theName);
        return $reflection->getValue($this);
    }
}

IMO, you shouldn't use __get and __set as a replacement for getters and setters. Since they are triggered when trying to access a non-accessible property, they are much more related to error-handling. And they are also much slower than a regular getter or setter.

like image 148
Gordon Avatar answered Mar 27 '23 02:03

Gordon