__set 和字符串连接
我想知道这是否可能:
我已经成功使用 __set() 魔术方法将值设置为类的属性:
class View
{
private $data;
public function __set( $key, $value )
{
$this->data[$key] = $value;
}
}
所以我能够:
$view = new View();
$view->whatever = 1234;
例如,当我想连接字符串时,问题就出现了。看起来 __set() 没有被调用(事实上它没有被调用)。
$view = new View();
$view->a_string = 'hello everybody'; //Value is set correctly
$view->a_string.= '<br>Bye bye!'; //Nothing happens...
echo $view->a_string;
这输出“大家好”。我无法在第二个作业中执行 __set() 。 阅读 php.net 它说:
__set() is run when writing data to inaccessible properties.
所以由于 a_string 已经存在,所以不会调用 __set 。 我的问题最后是......我怎样才能实现串联操作?
注意: 好吧...我一发布这篇文章,墨菲就来给我答案...
答案(据我所知)是 PHP 无法像我一样决定 a_string 是否可用没有定义 __get() 方法。
定义 __get() 允许 php 查找 a_string 的当前值,然后使用 __set() 连接该值。
Im' wondering if this is possible:
I've successfully used __set() magic method to set values to properties of a class:
class View
{
private $data;
public function __set( $key, $value )
{
$this->data[$key] = $value;
}
}
So I'm able to:
$view = new View();
$view->whatever = 1234;
The problem comes when I want to concatenate a string for example. It seems like __set() is not being called (it's not being called in fact).
$view = new View();
$view->a_string = 'hello everybody'; //Value is set correctly
$view->a_string.= '<br>Bye bye!'; //Nothing happens...
echo $view->a_string;
This outputs "hello everybody". I'm not able to execute __set() in the second assignment.
Reading php.net it says that:
__set() is run when writing data to inaccessible properties.
So as a_string already exists, __set is not called.
My question finally is... how could I achieve that concatenation operation??
Note:
Ok... Murphy came and gave me the answer as soon as I posted this...
The answer (As I understood), is that PHP is not able to decide if a_string is available as I didn't defined a __get() method.
Defining __get() allows php to find the current value of a_string, then uses __set() to concatenate the value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该添加一个 __get() 方法,该方法允许您访问不可访问的属性,就像使用 __set() 所做的那样。然后您可以执行以下操作:
__get() 方法将是:
You should add a __get() method that allows you to access inaccessable properties just as you did with __set(). You could then do the following:
The __get() method would be:
仅供参考,对于简单的分配,魔术方法甚至不是必需的。
这将工作得很好,因为 PHP 将通过赋值创建新属性。当需要对值运行额外的检查/代码时,通常使用 __set/get。
FYI, for simple assignment, magic methods aren't even necessary.
This will work just fine as PHP will create the new properties through assignment. __set/get usually is used when additional checks/code need to be run on the values.
这是因为 __set() 是一个方法而不是字符串。如果您希望它像字符串一样“起作用”,您可以将其更改为这样。
It's because __set() is a method and not a string. If you want it to "act" like a string you can change it to this.