views:

36

answers:

2

I have a class where I'm using __set. Because I don't want it to set just anything, I have an array of approved variables that it checks before it will actually set a class property.

However, on construct, I want the __construct method to set several class properties, some of which are not in the approved list. So when construct happens, and I do $this->var = $value, I of course get my exception that I'm not allowed to set that variable.

Can I get around this somehow?

+3  A: 

Declare the class members:

class Blah
{
   private $imAllowedToExist;   // no exception thrown because __set() wont be called
}
Coronatus
A: 

Declaring the class members is your best bet. If that doesn't work, you could have a switch ($this->isInConstructor?) which determines whether to throw the error.

On the other hand, you could also use the __get method as well as the __set method and have both of them map to a wrapped library:

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." );
        }
    }
}
Christopher W. Allen-Poole