PHP 分段错误 | __get 在类内部调用受保护的属性?
我有一个类,其中包含方法 __toString 和 __get 以及一些受保护的属性,例如“消息”。到目前为止,一切都很好。
现在的问题是我需要访问 __toString 中的 $this->message,当 $display_all 设置为 true 时(见下面的示例),这会导致(并非总是但经常)出现分段错误。你知道为什么以及如何解决它吗?
多谢 ! 罗尔夫
PS:这是一个例子
class FuckedClass {
protected $file;
protected $line;
protected $display_all;
protected $message;
//[...]
/**
* Magic getter
* @param String $name
* @return mixed
*/
public function __get($name) {
return (in_array($name,array_keys(get_class_vars(__CLASS__))))?
$this->$name : null;
}
/**
* Formats
*/
public function __toString() {
$message = $this->message . ($this->display_all) ?
'[ Location: '.$this->file.' @ line '.$this->line.' ]':
'';
$text =<<<PLAIN
Error : {$message}
PLAIN;
return $text;
}
}
//instantiated $fucked_class
die($fucked_class);
I have a class with the methods __toString and __get and some protected properties such as "message". So far, so good.
The problem now is that I need to access $this->message in __toString, and this causes (NOT ALWAYS BUT OFTEN) a segmentation fault when (see following example) $display_all is set to true. Do you know why and how to fix it ?
Thanks a lot !
Rolf
PS: here is an example
class FuckedClass {
protected $file;
protected $line;
protected $display_all;
protected $message;
//[...]
/**
* Magic getter
* @param String $name
* @return mixed
*/
public function __get($name) {
return (in_array($name,array_keys(get_class_vars(__CLASS__))))?
$this->$name : null;
}
/**
* Formats
*/
public function __toString() {
$message = $this->message . ($this->display_all) ?
'[ Location: '.$this->file.' @ line '.$this->line.' ]':
'';
$text =<<<PLAIN
Error : {$message}
PLAIN;
return $text;
}
}
//instantiated $fucked_class
die($fucked_class);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,
__toString
只是变量被输入为字符串时调用的方法,或者调用方法本身。它的行为与任何其他类方法一样,因此此代码必须有效:或者您可能在 __get 中遇到一些问题,请发布它的内容,我将编辑我的答案。
Actually,
__toString
is just a method called when variable is being typed to string, or the method itself is called. It behaves as any other class method, so this code must work:Or you may have some problem in the __get, please post it's contend and I'll edit my answer.
好吧,问题来自其他地方,我有类似
public function setDisplayAll(boolean $value) 的东西,而且方法参数的布尔类型似乎触发了错误(并且此类用于管理错误......)
抱歉,无论如何,感谢您的帮助,祝您有美好的一天!
OK, the problem was from somewhere else, I had something like
public function setDisplayAll(boolean $value), and it seems that this boolean typing for the method argument was triggering an error (and this class was used to manage errors ...)
sorry, thanks for your help anyway and have a good day !