php:在某些情况下避免获得?
我有一个类,我在其中使用php:在某些情况下避免获得?,php,get,magic-methods,Php,Get,Magic Methods,我有一个类,我在其中使用\uu set。因为我不希望它只设置任何东西,所以我有一个已批准的变量数组,它在实际设置类属性之前会检查这些变量 但是,在construct上,我希望\uu construct方法设置几个类属性,其中一些属性不在approved列表中。所以当构造发生时,我做了$this->var=$value,我当然会得到一个例外,我不允许设置那个变量 我能设法解决这个问题吗?声明类成员: class Blah { private $imAllowedToExist; // n
\uu set
。因为我不希望它只设置任何东西,所以我有一个已批准的变量数组,它在实际设置类属性之前会检查这些变量
但是,在construct上,我希望\uu construct
方法设置几个类属性,其中一些属性不在approved列表中。所以当构造发生时,我做了$this->var=$value
,我当然会得到一个例外,我不允许设置那个变量
我能设法解决这个问题吗?声明类成员:
class Blah
{
private $imAllowedToExist; // no exception thrown because __set() wont be called
}
声明类成员是您的最佳选择。如果这不起作用,您可以使用一个开关(
$this->isInConstructor
?)来确定是否抛出错误
另一方面,您也可以使用\uuu get
方法以及\uu 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." );
}
}
}