【发布时间】:2015-11-07 02:07:06
【问题描述】:
我目前正在制作一个基于对象的 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 中有测试代码,但它没有运行。
感谢任何帮助。
谢谢
【问题讨论】:
标签: php