对象外部可见的PHP私有属性(在同一类中)
在这个例子中,我有一个抽象类和两个常规类。抽象类不应单独使用,因此其构造函数受到保护。有些函数是在抽象类中定义的 其中一个函数是“克隆”函数,它应该返回当前对象的新实例。 此函数用于创建当前对象的副本 我的问题是:对象外部可见的PHP私有属性(在同一类中),php,class,properties,visibility,Php,Class,Properties,Visibility,在这个例子中,我有一个抽象类和两个常规类。抽象类不应单独使用,因此其构造函数受到保护。有些函数是在抽象类中定义的 其中一个函数是“克隆”函数,它应该返回当前对象的新实例。 此函数用于创建当前对象的副本 我的问题是: 当试图在clone()中设置$copy->baz([2])时,它会起作用,因为我属于定义此私有属性的类。但是,这对我来说没有意义(至少在本例中是这样),因为$copy是另一个对象(属于同一个类)——在设置另一个对象(不是类)的私有属性时,有可能强制PHP使用magic setter(
当试图在clone()中设置$copy->baz([2])时,它会起作用,因为我属于定义此私有属性的类。但是,这对我来说没有意义(至少在本例中是这样),因为$copy是另一个对象(属于同一个类)——在设置另一个对象(不是类)的私有属性时,有可能强制PHP使用magic setter(“设置私有属性”)吗
您需要将您的方法命名为
\uu clone
,而不是clone
[编辑以替换代码]
试试这个:
<?
header( 'content-type: text/plain' );
abstract class ac
{
private $name = 'default-value';
public function __set($name, $value)
{
throw new Exception( 'Undefined or private property.' . $name );
}
function __clone()
{
// this does work - $this->name is private but is accessible in this class
$this->name = 'Isaac Newton';
}
}
class c1 extends ac
{
function __clone()
{
// this does not work - $this->name is private to ac and can't be modified here
$this->name = 'Isaac Newton';
}
function echoName()
{
echo $this->name;
}
}
function dostuff()
{
$o = new c1();
//$o->otherVariable = 'test'; // won't work - it's undefined
$a = clone $o;
}
dostuff();
您需要命名您的方法\u clone
,而不是clone
[编辑以替换代码]
试试这个:
<?
header( 'content-type: text/plain' );
abstract class ac
{
private $name = 'default-value';
public function __set($name, $value)
{
throw new Exception( 'Undefined or private property.' . $name );
}
function __clone()
{
// this does work - $this->name is private but is accessible in this class
$this->name = 'Isaac Newton';
}
}
class c1 extends ac
{
function __clone()
{
// this does not work - $this->name is private to ac and can't be modified here
$this->name = 'Isaac Newton';
}
function echoName()
{
echo $this->name;
}
}
function dostuff()
{
$o = new c1();
//$o->otherVariable = 'test'; // won't work - it's undefined
$a = clone $o;
}
dostuff();
请查看我对答案的最新编辑-我认为这可能会有所帮助。请查看我对答案的最新编辑-我想这可能会有所帮助。谢谢
<?
header( 'content-type: text/plain' );
abstract class ac
{
private $name = 'default-value';
public function __set($name, $value)
{
throw new Exception( 'Undefined or private property.' . $name );
}
function __clone()
{
// this does work - $this->name is private but is accessible in this class
$this->name = 'Isaac Newton';
}
}
class c1 extends ac
{
function __clone()
{
// this does not work - $this->name is private to ac and can't be modified here
$this->name = 'Isaac Newton';
}
function echoName()
{
echo $this->name;
}
}
function dostuff()
{
$o = new c1();
//$o->otherVariable = 'test'; // won't work - it's undefined
$a = clone $o;
}
dostuff();