繁体   English   中英

如何从子类访问父属性? PHP

[英]How do I access parent property from subclass? PHP

我在从子级类访问顶级变量时遇到问题。 这是一个例子...

应用程序.php:

class Application {
    var $config;
    var $db;

    function __construct() {
        include_once('Configuration.php');
        include_once('Database.php');
        $this->config   = new Configuration;
        $this->db       = new Database;
    }
}

配置.php:

class Configuration {
    var $dbhost = 'localhost';
}

数据库.php:

class Database {
    function __construct() {
        echo parent::config->dbhost;
    }
}

我很清楚,这里使用parent是错误的,因为子类没有扩展父类,但我如何访问它?

谢谢你。

您应该创建一个在其构造中创建$db链接的Base类。 然后让所有需要数据库访问的类扩展该类。 您在此处使用“父类”的命名法不正确。

class Base {
   private $db;   // Make it read-only

   function __construct() {
      $this->db = DB::connect();    // It's a good practice making this method static
   }

   function __get($property) {
      return $this->$property;
   }
}

class Application {
    public $config;

    function __construct() {
        parent::__construct();

        require_once 'Configuration.php';
        require_once 'Database.php';
        $this->config   = new Configuration();
    }

    function random_function() {
       $this->db(....)    // Has full access to the $db link
    }
}

父符号用于访问对象层次结构中对象的父对象。 你在这里做的是试图找到来电者,而不是父母

您这样做的方法是将您的配置实例传递给数据库对象。

    class Database {
          protected $config;

          public function __construct(Configuration $config){
                $this->config = $config;
          }

          public function connect(){
                //use properties like $this->config->username to establish your connection. 
          }
    }

当您扩展类并使子类调用父类上的方法时,将使用父表示法。

    class MySuperCoolDatabase extends Database {
          protected $is_awesome; 

          public function __construct(Configuration $config){
               // do all the normal database config stuff
               parent::__construct($config);
               // make it awesome
               $this->is_awesome = true;
          }
    }

这定义了一个子类,它是一个类型定义,其作用与基类相同,但实现略有不同。 这样的实例仍然可以说是一个数据库......只是一种不同类型的数据库。

好吧,虽然我认为 Orangepills 的答案更好。 如果您不想使用它并且由于所有变量都是公开的,您可以简单地传递这样的变量:

class Application {
    var $config;
    var $db;

    function __construct() {
        include_once('Configuration.php');
        include_once('Database.php');
        $this->config   = new Configuration;
        $this->db       = new Database($this->config->dbhost);
    }
}

class Configuration {
    var $dbhost = 'localhost';
}

class Database {
    function __construct($dbhost) {
        echo $dbhost;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM