[英]Access Property of class in parent namespace
I have two class, main class is app.php in root directory, and db.php in \\system How To Get property $config in class base, with namespace pattern?? 我有两个类,主类是根目录中的app.php和\\ system中的db.php如何在类库中使用命名空间模式获取属性$ config? I want to get $config in class base, this is what I want
我想在类库中获取$ config,这就是我想要的
I define config for hostname,user,pass then I declare base class wit new \\App\\base I can get config in class db 我为主机名,用户,密码定义配置,然后声明基类wit new \\ App \\ base我可以在类db中获取配置
<?php
// \App.php
namespace App;
class base{
private $config;
private $db;
function __construct($config){
$this->config = $config;
$this->db = new \App\system\db;
}
public function getTest() {
return $this->test;
}
}
function load($namespace) {
$splitpath = explode('\\', $namespace);
$path = '';
$name = '';
$firstword = true;
for ($i = 0; $i < count($splitpath); $i++) {
if ($splitpath[$i] && !$firstword) {
if ($i == count($splitpath) - 1) {
$name = $splitpath[$i];
} else {
$path .= DIRECTORY_SEPARATOR . $splitpath[$i];
}
}
if ($splitpath[$i] && $firstword) {
if ($splitpath[$i] != __NAMESPACE__) {
break;
}
$firstword = false;
}
}
if (!$firstword) {
$fullpath = __DIR__ . $path . DIRECTORY_SEPARATOR . $name . '.php';
return include_once ($fullpath);
}
return false;
}
function loadPath($absPath) {
return include_once ($absPath);
}
spl_autoload_register(__NAMESPACE__ . '\load');
?>
<?php
// \System\db.php
namespace App\system;
class db{
private $config;
function __construct(){
$this->config = "How To Get property $config in class base, with namespace pattern??";
}
}
?>
I would suggest you something like this: 我建议你这样:
class db{
private $test;
function __construct(){
include('../app.php');
$app = new base();
$this->test = $app->getTest();
}
}
Well, just pass the config when you create the db object. 好了,在创建db对象时只需传递配置即可。 Also use the
use
keyword for better readability. 还可以使用
use
关键字来提高可读性。
\\App \\ App
namespace App;
use \App\system\db;
class base {
private $config;
private $db;
function __construct($config){
$this->config = $config;
$this->db = new db($config);
}
public function getTest() {
return $this->test;
}
}
\\System\\db.php \\ System \\ db.php
namespace App\system;
class db {
private $config;
function __construct($config){
$this->config = $config;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.