【问题标题】:PHP Catchable fatal error: Object of class webhook could not be converted to stringPHP Catchable 致命错误:类 webhook 的对象无法转换为字符串
【发布时间】:2016-02-03 17:58:29
【问题描述】:

下面我的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();

【问题讨论】:

  • 这个$object->$this->callable_method( $this->event->data ); 的解析肯定不是你所期望的。试试$object->{$this->callable_method}( $this->event->data );

标签: php object fatal-error


【解决方案1】:

告诉php如何解析这样的结构:

$object->$this->callable_method( $this->event->data );

改为:

$object->{$this->callable_method}( $this->event->data );

【讨论】:

    【解决方案2】:

    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 );

    【讨论】:

    • 很好的解释李!现在完全有道理了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2015-03-08
    • 2013-08-07
    • 2021-07-09
    相关资源
    最近更新 更多