![](/img/trans.png)
[英]PHP - Catchable fatal error: Object of class could not be converted to string
[英]PHP Catchable fatal error: Object of class webhook could not be converted to string
我下面的webhook
类以及测试会产生该错误。 当我echo
$this->callable_object
它输出invoice
,当我echo
$this->callable_method
它输出created
。 由于某种原因,该行return $object->$this->callable_method( $this->event->data );
产生该错误,我不确定为什么吗? 它应该与$invoice->created( $args );
班级+考试
class webhook {
private $event;
private $callable_object;
private $callable_method;
private $types = array(
'invoice.created',
'invoice.payment_failed',
'invoice.payment_succeeded',
'invoice.updated'
);
public function __construct( $event ) {
$this->event = $event;
$this->valid();
$this->parse();
}
public function valid() {
if( !in_array( $this->event->type, $this->types ) ) {
throw new Exception( 'unknown event' );
}
}
public function parse() {
$parts = explode( '.', $this->event->type );
$this->callable_object = $parts[0];
$this->callable_method = $parts[1];
}
public function get_event_type() {
return $this->event->type;
}
public function get_event_data() {
return $this->event->data;
}
public function get_callable_object() {
return $this->callable_object;
}
public function get_callable_method() {
return $this->callable_method;
}
public function execute() {
$object = new $this->callable_object();
return $object->$this->callable_method( $this->event->data );
}
}
$event['type'] = 'invoice.created';
$webhook = new webhook( (object)$event );
$webhook->execute();
告诉php如何解析这样的构造:
$object->$this->callable_method( $this->event->data );
改成:
$object->{$this->callable_method}( $this->event->data );
u_mulder在他的解决方案中是正确的,但也可以进一步解释...
这是您当前的内容: $object->$this->callable_method( $this->event->data );
PHP将尝试将这些属性递归到callable_method
,这意味着它正在$object
上寻找$this
属性,并且由于$this
无法转换为字符串,因此会出现错误。
这基本上就像在数学中一样,条件是以下1+1x1+1
的结果将是3
,而实际上是(1+1)x(1+1)
会是4
。 我们在“数学”中添加了括号以增加重要性(请不要误解我的术语,您会明白的)
就像在数学中一样,我们可以对PHP进行同样的操作,但是我们使用花括号代替
$object->{$this->callable_method}( $this->event->data );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.