在OO PHP中使用__set()设置属性值

时间:2014-06-24 20:34:29

标签: php oop set

我正在通过OO PHP创建网页。我的班级顶部有4个公共属性:

class page {
    public $content;
    public $title = 'Default Title';
    public $buttons = array("Home"=>'index.php',
                            "Contact"=>'contact.php',
                            "Service"=>'service.php',
                            "About Us"=>'aboutus.php');
    public $keywords = 'These,are,the,keywords';

    // The __set() function should change the value of attributes.
    public function __set($name,$value){
        $this->name=$value;
    }

我有一个名为Display()的方法,它向用户显示我的所有内容:

public function Display(){
    echo "<html>\n<head>\n";
    $this->DisplayTitle();
    $this->DisplayKeywords();
    $this->DisplayStyle();
    echo "</head>\n<body>\n";
    $this->DisplayHeader();
    $this->DisplayMenu($this->buttons);
    echo $this->content;
    $this->DisplayFooter();
    echo "</body>\n</html>\n";
}

现在我遇到的问题是当我想从&#39;默认标题&#39;更改标题属性的默认值时说'主页&#39;使用__set()构造函数根本没有任何反应。

    $homepage->__set('title','Home Page');

我在一个单独的php文件上创建了一个名为$homepage的处理程序。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

你调用函数的方式错了,你定义函数的地方也错了。

__set,如文档here所述,是一项神奇的功能。因此,您不需要以您的方式调用它。但是,如果您想以这种方式调用它,我建议您将其重命名为set,以免遇到问题。

调用函数就像这样简单:

$homepage->title = 'Home Page';

这是因为在设置类的变量时调用__set。声明函数时也会出现问题:

public function __set($name,$value){
    $this->name=$value;
}

这总是将变量name设置为您的值。您需要将其更改为:

public function __set($name, $value) {
    $this->$name = $value;
}

这应该按预期工作。

答案 1 :(得分:0)

__set()方法更改

$this->name=$value;

$this->$name=$value;