Php: avoid __get in certain circumstances?

I have a class in which I use __set. Since I don't want it to set just anything, I have an array of validated variables that it checks before it actually sets the class property.

However, in the constructor, I want the method to __constructset several class properties, some of which are not listed in the approved list. Therefore, when the construction occurs, and I do $this->var = $value, I, of course, get my exception that I am not allowed to set this variable.

Can I get around this somehow?

+3
source share
2 answers

Declare class members:

class Blah
{
   private $imAllowedToExist;   // no exception thrown because __set() wont be called
}
+4

- . , ($this->isInConstructor?), , .

, __get, __set, :

class Foo
{
    private $library;        
    private $trustedValues;

    public function __construct( array $values )
    {
        $this->trustedValues = array( 'foo', 'bar', 'baz' );
        $this->library = new stdClass();
        foreach( $values as $key=>$value )
        {
            $this->library->$key = $value;
        }
    }

    public function __get( $key )
    {
        return $this->library->$key;
    }

    public function __set( $key, $value )
    {
        if( in_array( $key, $this->trustedValues ) )
        {
            $this->library->$key = $value;
        }
        else
        {
            throw new Exception( "I don't understand $key => $value." );
        }
    }
}
+1

Source: https://habr.com/ru/post/1737562/


All Articles