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
];
}
我需要访问子类中的父类数组值。但是这个$settings->constants['database']['APP_DB_HOST']
由于某种原因不起作用。
答案 0 :(得分:1)
这是工作解决方案
<?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());
输出:
Constants Object
(
[database] =>
[constants] => Array
(
[database] => Array
(
[APP_DB_HOST] => localhost
)
)
)
根据你的评论, 如果你想在其他类函数中执行它,你也可以这样做。
class Constants extends Settings {
public $database;
public function useParentHost(){
$this->database = [
'APP_DB_HOST' => $this->constants['database']['APP_DB_HOST'], // working
];
return $this->database;
}
}
然后
$test = new Constants();
print_r($test->useParentHost());
你必须声明一些函数才能使用$this
,在function
之外没有/这会导致错误。
答案 1 :(得分:0)
变量$ settings不存在,也许你的意思是$ this?
$this->constants['database']['APP_DB_HOST'];
享受。