gpt4 book ai didi

PHP __set 魔术方法未被调用

转载 作者:行者123 更新时间:2023-12-04 02:16:04 25 4
gpt4 key购买 nike

我目前正在制作一个基于对象的 API。我有一个名为 Part 的抽象类,每个 child 都会扩展它。 Part 有一个 __set 函数,它将值存储在一个名为 $attributes 的 protected 数组中。但是,当我执行 $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 中有测试代码,但它没有运行。

感谢任何帮助。

谢谢

最佳答案

The __set magic method is called only when a property is inaccessible from the context in which it is set .因为 Client 扩展 PartPart 的属性都可以在 Client 中访问,所以魔术方法不是需要。

关于PHP __set 魔术方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33578383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com