因此,我开始为一个用于学习目的的微框架编写引导脚本(同时学习更多关于编程、php和oop的知识),我遇到了这种奇怪的意外行为。
启动config()类新对象的变量$config在公共的Bootstrap的__construct中被调用,然后在也是公共的Bootstrap的__destruct中使用。$config的变量本身是公共的,并且在__construct之前声明,如下所示。
现在,奇怪的是,我在__destruct中使用$config时收到了一个通知和致命错误,它说变量不存在,而致命错误是在非对象上调用成员函数(因为$config不存在)
这是剧本,希望有人能指出为什么会发生这种奇怪的行为,我可能错过了什么,这种行为是有道理的,但好吧,我错过了,然后请指出。
<?php
basename($_SERVER["PHP_SELF"]) == "bootstrap.php" ? die("No direct script access allowed") : '';
class Bootstrap
{
public $config;
protected $start_route;
public function __construct()
{
$this->settings();
$config = new Config();
$this->database();
$this->routing();
$start_route = new Route($config);
$start_route->initiate();
}
public function run()
{
$db_info = new DatabaseInfo();
$database = new Database([
'database_type' => $db_info->get_db('dbdriver'),
'database_name' => $db_info->get_db('database'),
'server' => $db_info->get_db('hostname'),
'username' => $db_info->get_db('username'),
'password' => $db_info->get_db('password'),
'charset' => $db_info->get_db('dbcharset'),
'port' => $db_info->get_db('port'),
'prefix' => $db_info->get_db('dbprefix'),
// driver_option for connection, read more from
// http://www.php.net/manual/en/pdo.setattribute.php
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL
]
]);
/*
*
* Read is much faster than Write,
* while INSERT will increase load time by ~40ms per each query,
* COUNT will only increase by ~2ms
*
*/
$count = $database->count('site_log', [
'log_type' => 1
]);
/*
$database->insert('site_log', [
'remote_addr' => '127.0.0.1',
'request_uri' => '/',
'log_type' => 1,
'message' => 'Test Query'
]);
*/
echo 'The are ' . $count . ' rows in log with severity level of 1!<br />';
}
// Since it's being called from __constrcut, it will run before run()
private function settings()
{
require BOOTPATH.'core''config'.CLASSFIX.EXT;
}
// Since it's being called from __constrcut, it will run before run()
private function database()
{
require BOOTPATH.'core''database'.CLASSFIX.EXT;
return;
}
// Since it's being called from __constrcut, it will run before run()
private function routing()
{
require BOOTPATH.'core''router'.CLASSFIX.EXT;
return;
}
// Since it's being outputed within __destrcut, it will run after run() and basically last
public function __destruct()
{
$script_end = (float) array_sum( explode( ' ',microtime() ) );
echo 'Welcome to ' . $config->get_conf('site_name') . '<br />';
echo 'Processing time: '. sprintf( '%.4f', ( $script_end - APP_START ) ).' seconds';
}
}
执行此操作时:
$config = new Config();
如果要在构造函数的作用域中创建新的$config
对象,则没有填充Bootstrap
类的$config
属性
您必须使用$this->config
;访问类属性