1
<?php
class classname
{
public $attribute;
function __get($name)
{
return 'here:'.$this->$name;
}
function __set ($name, $value)
{
$this->$name = $value;
}
}
$a = new classname();
$a->attribute = 5;
echo $a->attribute;

当我运行上面的脚本时,它显示:5

问题:

echo $a->attribute;这行代码会调用function __get($name),对吧?那么为什么它不显示:here:5

4

3 回答 3

2

您将属性标记为公开,因此可以从类外部访问该属性。

__get() 用于从不可访问的属性中读取数据。

http://www.php.net/manual/en/language.oop5.overloading.php#object.get

如果你想强制任意属性使 __get 和 __set 被调用,你可以将它们存储在私有映射中:

class classname
{
    private $vars = array();
    function __get($name)
    {
        return 'here:'.$this->vars[$name];
    }
    function __set ($name, $value)
    {
        $this->vars[$name] = $value;
    }
}
于 2013-07-22T02:55:51.510 回答
1

魔术 __get 和 __set 和 __call 仅在属性属性或方法未定义或无法从调用范围访问或未定义时调用。

要完成这项工作,您必须删除对属性的公共引用或使其受保护或私有。

class classname
{
  protected $attribute;
  function __get($name)
  {
    return 'here:'.$this->$name;
  }
  function __set ($name, $value)
  {
    $this->$name = $value;
  }
}
$a = new classname();
$a->attribute = 5; //  calling __set
echo $a->attribute; // calling __get
于 2013-07-22T02:56:04.037 回答
0

这里的“属性”是公开的,所以不会调用 __get() 魔法方法。

于 2013-07-22T02:56:44.013 回答