没有调用PHP __set魔术方法

时间:2015-11-07 02:07:07

标签: php

我目前正在制作一个基于对象的API。我有一个名为Part的抽象类,每个孩子都会延伸。 Part有一个__set函数,用于将值存储在名为$attributes的受保护数组中。但是,当我执行$part->user = new User(etc...);时,它不会运行__set函数。这是我的代码:

部分:

<?php

namespace Discord;

abstract class Part
{
    protected $attributes = [];

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;

        if (is_callable([$this, 'afterConstruct'])) {
            call_user_func([$this, 'afterConstruct']);
        }
    }

    /**
     * Handles dynamic get calls onto the object.
     * 
     * @param  string $name 
     * @return mixed
     */
    public function __get($name)
    {
        $str = '';

        foreach (explode('_', $name) as $part) {
            $str .= ucfirst($name);
        }

        $funcName = "get{$str}Attribute";

        if (is_callable([$this, $funcName])) {
            return call_user_func([$this, $funcName]);
        }

        if (!isset($this->attributes[$name]) && is_callable([$this, 'extraGet'])) {
            return $this->extraGet($name);
        }

        return $this->attributes[$name];
    }

    /**
     * Handles dynamic set calls onto the object.
     *
     * @param string $name 
     * @param mixed $value 
     */
    public function __set($name, $value)
    {
        echo "name: {$name}, value: {$value}";
        $this->attributes[$name] = $value;
    }
}

客户端:

<?php

namespace Discord\Parts;

use Discord\Part;
use Discord\Parts\User;

class Client extends Part
{
    /**
     * Handles extra construction.
     * 
     * @return void
     */
    public function afterConstruct()
    {
        $request = json_decode($this->guzzle->get("users/{$this->id}")->getBody());

        $this->user = new User([
            'id'        => $request->id,
            'username'  => $request->username,
            'avatar'    => $request->avatar,
            'guzzle'    => $this->guzzle
        ]);
    }

    /**
     * Handles dynamic calls to the class.
     *
     * @return mixed 
     */
    public function __call($name, $args)
    {
        return call_user_func_array([$this->user, $name], $args);
    }

    public function extraGet($name)
    {
        return $this->user->{$name};    
    }
}

当我创建Client的新实例时,它会自动创建一个User实例并进行设置。但是,我在__set中测试了代码并且它没有运行。

感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:3)

The __set magic method is called only when a property is inaccessible from the context in which it is set。由于Client扩展了PartPart的属性都可以在Client中访问,因此不需要神奇的方法。

相关问题