我有这个类用于注册表类:
namespace App\Core;
final class Registry {
private $data = array();
/**
* @param string $key
*
* @return mixed
*/
public function get($key) {
return (isset($this->data[$key]) ? $this->data[$key] : null);
}
/**
* @param string $key
* @param string $value
*/
public function set($key, $value) {
$this->data[$key] = $value;
}
/**
* @param string $key
*
* @return bool
*/
public function has($key) {
return isset($this->data[$key]);
}
}
而这个主控制器:
namespace App\Core;
use App\Core\Registry;
abstract class Controller {
protected $registry;
public function __construct($registry) {
$this->registry = $registry;
}
public function __get($key) {
return $this->registry->get($key); //error line
}
public function __set($key, $value) {
$this->registry->set($key, $value);
}
}
并需要在索引控制器中获取值:
namespace App\Catalog\Controller;
class IndexController extends \App\Core\Controller {
public function __construct()
{
}
public function index(){
$this->db->query();
}
}
在db类中:
namespace App\Core;
class Db {
public function __construct()
{
}
public function query(){
echo 'Im query';
}
}
现在在主索引中我添加:
require '../vendor/autoload.php';
$registry = new App\Core\Registry();
use App\Core\Db;
$registry->set('db', new Db());
在行动中,我需要从 Db
类打印 Im query
但我看到这个错误:
致命错误:未捕获错误:在/Applications/MAMP/htdocs/mvc/application/Core/Controller.php:16中调用null上的成员函数get()堆栈跟踪:#0 / Applications / MAMP / htdocs / mvc / application / Catalog / Controller / IndexController.php(13):App \ Core \ Controller - > __ get('db')#1 [内部函数]:App \ Catalog \ Controller \ IndexController-> index()#2 / Applications / MAMP / htdocs / mvc / application / Core / System / Route.php(649):call_user_func_array(Array,Array)#3 /Applications/MAMP/htdocs/mvc/application/Core/System/Route.php(599):Apple \ Core \ System \ Route-> callback(Array,Array)#4 /Applications/MAMP/htdocs/mvc/public/index.php(63):App \ Core \ System \ Route-> end()#5 在第16行的/Applications/MAMP/htdocs/mvc/application/Core/Controller.php中抛出
注意:我使用composer PSR-4加载所有类,如下所示:
"autoload": {
"psr-4": {"App\\": "application/"}
}
怎么办可以解决这个错误?!