[英]php - Access parent class array in child class
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database = [
'APP_DB_HOST' => $settings->constants['database']['APP_DB_HOST'], // not working
];
}
I need to access parent class array values in child class. 我需要访问子类中的父类数组值。 but this
$settings->constants['database']['APP_DB_HOST']
is not working for some reason. 但这
$settings->constants['database']['APP_DB_HOST']
由于某种原因无法正常工作。
Here is the working solution 这是工作解决方案
<?php
class Settings {
public $constants = [
'database' => [
'APP_DB_HOST' => 'localhost'
],
];
}
class Constants extends Settings {
public $database;
public function __construct(){
$database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
}
}
print_r(new Constants());
outputs: 输出:
Constants Object
(
[database] =>
[constants] => Array
(
[database] => Array
(
[APP_DB_HOST] => localhost
)
)
)
as per your comment, if you want to do it in other class function, you can do that as well. 根据您的评论,如果要在其他类函数中执行此操作,也可以执行此操作。
class Constants extends Settings {
public $database;
public function useParentHost(){
$this->database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
return $this->database;
}
}
and then 接着
$test = new Constants();
print_r($test->useParentHost());
you have to declare some function to use $this
, without/outside the function
this will cause an error. 您必须声明一些函数以使用
$this
,而在该function
外部/外部将导致错误。
The variable $settings does not exist, perhaps you mean $this? 变量$ settings不存在,也许您是说$ this?
$this->constants['database']['APP_DB_HOST'];
Enjoy. 请享用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.