PHP |改变课堂内的功能

时间:2015-06-10 22:55:01

标签: php function class parameters

我想在PHP中创建一个守护进程构造函数。

class DAEMON {
    var host;
    var port;
    function __construct($host, $port) {
        $this -> host = $host;
        $this -> port = $port;
    }
    function start() {
        while (true) {
            $this->loop();
        }
    }
    function loop() {

    }
}

除了传递$ host和$ port参数,如

$server = new DAEMON("127.0.0.1", 9000);
$server -> start();

我想以某种方式将loop()函数作为第三个参数传递,因此它会覆盖loop()函数或在其中注入代码。

我试过

$server = new DAEMON("127.0.0.1", 9000, function() {
    // function() can't take any parameters
    // I cant use $server variable here
});
$server -> start();

$server = new DAEMON("127.0.0.1", 9000);
$server::loop = function() {
    //not working, it's not javascript
};
$server->start();

都没有工作。我该怎么做?我一直在努力寻找解决方案......

3 个答案:

答案 0 :(得分:2)

您只需将匿名函数传递给构造函数

即可

http://php.net/manual/en/functions.anonymous.php

<?php

class DAEMON {
    private $host;
    private $port;
    private $callback;

    public function __construct($host, $port, $callback) {
        $this->host = $host;
        $this->port = $port;
        if ( ! is_callable($callback)) {
            throw new InvalidArgumentException('callback needs to be a function');
        }

        $this->callback = $callback;
    }

    public function start() {
        $callback = $this->callback;
        while (true) {
            $callback($this);
        }
    }
}

$server = new DAEMON("127.0.0.1", 9000, function($server) {
    echo "hello_world";
});

$server->start();

答案 1 :(得分:1)

您可以调用use语言构造将参数传递给匿名函数。在您的情况下,如果您想使用$server变量,那么您可以执行..

$server = new DAEMON("127.0.0.1", 9000, function() use ($server){
    // function() can't take any parameters
    // I cant use $server variable here
});
$server -> start();

...但为了实现这一点,您的DAEMON{}类应该在接受callable类型的构造函数中有第三个参数..

答案 2 :(得分:0)

我不确定允许函数运行任意代码的实际原因,但是你可以通过执行string as php code来做一些非常脏的事情。

class DAEMON {
    private $host;
    private $port;
    private $injection;

    public function __construct($host, $port, $injection) {
        $this->host = $host;
        $this->port = $port;
        $this->injection = $injection;
    }
    public function start() {
        while (true) {
            $this->loop();
        }
    }
    private function loop() {
        eval($this->injection);
    }
}