在PHP中创建和使用魔术方法

Som*_*son 3 php magic-methods

我试图掌握PHP的魔术方法,为此我创建了一个如下所示的测试类:

<?php
class overload
{
    protected $lastCalledParam;

    public $param;

    public function __construct() 
    {
        return $this->switchConstruct(func_get_args());
    }

    protected function switchConstruct(array $args)
    {
        switch (count($args))
        {
            case 0:
                return print "0 params<br />";
            case 1:
                return call_user_func_array(array($this, 'constr1'), $args);
            case 2:
                return call_user_func_array(array($this, 'constr2'), $args);
        }
        die("Invalid number of args");  
    }

    protected function constr1($a) 
    {
        print "constr1 called<br />";
    }

    protected function constr2($a, $b) 
    {
        print "constr2 called<br />";
    }

    public function __get($name)
    {
        $this->lastCalledParam = $name;
        return $this->{$name};
    }

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

    protected function lastCalled()
    {
        if (func_num_args() == 1)
        {
            $args = func_get_args();
            $this->lastCalledParam = $args[0];
        }
        return $this->lastCalledParam;
    }

    public function __toString()
    {
        return $this->lastCalledParam == null ? "No data found" : $this->lastCalledParam;
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

<?php

require_once 'clib/overload.php';

$c = new overload();
print $c->__toString();
print "<br />";
$c->param = "Hello";
print $c->__toString();
?>
Run Code Online (Sandbox Code Playgroud)

我期待的行为是,在第一次__toString()通话时,会有:

0参数
没有找到数据
你好

但我得到的是:

0参数未
找到
数据未找到数据

我已经找到了一个主要的关键点,并且无法理解为什么它没有做设置lastCalledParam属性的工作!

我得到了总共0个错误和0个警告,并且启用了完整的错误和警告报告,所以我不明白什么是未被调用,在哪里/为什么.

dec*_*eze 6

__set仅在无法正常访问参数时才会调用.你public $param需要protected至少__set被调用.

__set()在将数据写入不可访问的属性时运行.

http://php.net/manual/en/language.oop5.overloading.php#object.set(强调我的)