I'm trying to call directly a returned function and passing an argument, but it seems I have to do it in two times.
This is my code:
<?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);
}
}
?>
This is IOC class:
<?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];
}
}
?>
I would like to transform this:
$dbh = $ioc->dbh;
$dbh = $dbh($dbInfos);
by this unique line of code:
$dbh = $ioc->dbh($dbInfos);
But I have an error if I do that:
Fatal error: Call to undefined method IOC::dbh() in domain.com/public/index.php on line 34
That doesn't make sense to me. Does someone know how to deal with this ?