I want to pass anonymous function to class constructor and assign it to its property but it is always null regardless of what i do, is that possible to do?
Sorry guys, it seems that class also extends Thread from php pthread extension: http://php.net/manual/en/book.pthreads.php , which seems to be the issue somehow.
<?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);
There shouldn't be any reason why it wouldn't work. I ran your code example, but it threw syntax errors so I corrected them and here is what I came up with:
<?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);
And this was the output after it ran:
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>"
}
}