访问父命名空间中的类的属性

时间:2014-09-07 09:03:26

标签: php

我有两个类,主类是根目录中的app.php,而\ system中是db.php 如何在类库中获取属性$ config,使用命名空间模式? 我想在类库中获得$ config,这就是我想要的

我为hostname,user,pass定义配置 然后我声明基类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??";
    } 
}
?>

2 个答案:

答案 0 :(得分:0)

我建议你这样:

class db{
  private $test;
  function __construct(){
    include('../app.php');
    $app = new base();
    $this->test = $app->getTest();
  } 
}

答案 1 :(得分:0)

好吧,只需在创建db对象时传递配置。另外,请使用use关键字以提高可读性。

<强> \应用

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中

namespace App\system;

class db {
    private $config;
    function __construct($config){
        $this->config = $config;
    } 
}
相关问题