如何在php中直接调用返回的匿名函数

时间:2014-09-06 20:52:27

标签: php dependencies callable

我正在尝试直接调用返回的函数并传递参数,但似乎我必须在两次内完成。

这是我的代码:

<?php
    $signup_db = $configOptions['db']['signup_db'];

    // setup the infos of the db connection in an object
    $dbInfos = new DBInfos();
    $dbInfos->setEngine( $signup_db['engine'] );
    $dbInfos->setHost( $signup_db['host'] );
    $dbInfos->setDbName( $signup_db['dbname'] );
    $dbInfos->setUser( $signup_db['user'] );
    $dbInfos->setPassword( $signup_db['password'] );

    // create the Inversion of Control object for dependency injection.
    $ioc = new IOC();

    // create a new database connection with a PDO object.
    $ioc->dbh = function($dbInfos) {
        try {
            PDOconfig::setDbInfos($dbInfos);
            $dbh = new PDOconfig();
            $dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (Exception $e) {
            echo "Error!: " . $e->getMessage() . "<br/>";
        }
        return $dbh;
    };

    $dbh = $ioc->dbh;
    $dbh = $dbh($dbInfos);

    // default page if empty.
    if (empty($_GET)) {
        $_GET["page"] = "home";
    }
    if (isset($_GET["page"])) {
        $page = $_GET["page"];
        $variables = array("page" => $page, 
                           "ioc" => $ioc);

        if ($page == "home") {
            renderLayoutWithContentFile("home.php", $variables);            
        } else if ($page == "contact") {
            renderLayoutWithContentFile("contact.php", $variables);
        } else if ($page == "about") {
            renderLayoutWithContentFile("about.php", $variables);
        }
    }  
?>

这是IOC课程:

<?php

// Inversion of control with magic methods
// its pupose is to serve as a container for dependency injection
class IOC {
    private $registry = array();

    public function __set($name, $resolver) {
        $this->registry[$name] = $resolver;
    }

    public function __get($name) {
        return $this->registry[$name];
    }
}

?>

我想改变这个:

$dbh = $ioc->dbh;
$dbh = $dbh($dbInfos);

这段独特的代码:

$dbh = $ioc->dbh($dbInfos);

但如果我这样做,我会有错误:

Fatal error: Call to undefined method IOC::dbh() in domain.com/public/index.php on line 34

这对我没有意义。 有人知道如何处理这件事吗?

1 个答案:

答案 0 :(得分:0)

这些行正在做什么:

$dbh = $ioc->dbh;
$dbh = $dbh($dbInfos);

$dbh被分配给一个函数,然后您将$dbInfos传递给它。虽然您要做的是调用函数dbh,其中$dbInfos类的参数IOC实际上并不存在。看看这里的区别......这就是为什么你得到未定义的调用错误。

如果您真的想这样做,请尝试在IOC课程中创建一个功能,然后继续您正在做的事情,即$dbh = $ioc->dbh($dbInfos); ..

我希望这有帮助..