分配给构造函数中的类属性的PHP匿名函数始终为null?

时间:2016-02-12 01:34:17

标签: php

我想将匿名函数传递给类构造函数并将其分配给它的属性,但无论我做什么,它总是为空,是否可以这样做?

对不起伙计们,似乎该类还从php pthread扩展中扩展了Thread: http://php.net/manual/en/book.pthreads.php,这似乎是一个问题。

<?php
$execute_action = function ($site, $response) {
    $siteTest = $site;
    echo $siteTest;
    echo $response;
};

class TestClass extends Thread
{
    public $execute_action;

    function __construct($execute_action)
    {
        $this->execute_action = $execute_action;
        var_dump($this->execute_action); // <- Null

        $this->execute_action = Closure::bind($execute_action, $this);
        var_dump($this->execute_action); // <- Null

        $this->execute_action = $execute_action->bindTo($this);
        var_dump($this->execute_action); // <- Null
    }
}

$test = new TestClass($execute_action);

1 个答案:

答案 0 :(得分:0)

不应该有任何理由不起作用。我运行了你的代码示例,但它抛出了语法错误,所以我纠正了它们,这就是我想出的:

<?php
class TestClass
{
    public $execute_action;
    public function __construct($execute_action)
    {
        $this->execute_action = $execute_action;
        var_dump($this->execute_action);
        $this->execute_action = Closure::bind($execute_action, $this);
        var_dump($this->execute_action);
        $this->execute_action = $execute_action->bindTo($this);
        var_dump($this->execute_action);die();
    }
} // Missing close brace

$execute_action = function ($site, $response) {
    $siteTest = $site;
    echo $siteTest;
    echo $response;
}; // Missing semi-colon

$test = new TestClass($execute_action);

这是它运行后的输出:

object(Closure)#1 (1) {
  ["parameter"]=>
  array(2) {
    ["$site"]=>
    string(10) "<required>"
    ["$response"]=>
    string(10) "<required>"
  }
}
object(Closure)#3 (2) {
  ["this"]=>
  object(TestClass)#2 (1) {
    ["execute_action"]=>
    *RECURSION*
  }
  ["parameter"]=>
  array(2) {
    ["$site"]=>
    string(10) "<required>"
    ["$response"]=>
    string(10) "<required>"
  }
}
object(Closure)#4 (2) {
  ["this"]=>
  object(TestClass)#2 (1) {
    ["execute_action"]=>
    *RECURSION*
  }
  ["parameter"]=>
  array(2) {
    ["$site"]=>
    string(10) "<required>"
    ["$response"]=>
    string(10) "<required>"
  }
}