【发布时间】:2019-07-25 02:20:32
【问题描述】:
我在构造函数中设置变量值。
为了保持一切井井有条,我创建了其他类,它们只会在“应用程序”类中实例化一次。
我想将受保护的变量值传递给其他类(前端,后端......)。我知道我们可以在这些类中创建相同的变量并将变量作为参数传递。这会导致大量的代码重复。
有没有更好的办法?
谢谢
class application{
protected $name;
protected $version;
protected $slug;
public function __construct(){
$this->name = $name;
$this->version = $version;
$this->slug = $slug;
$this->includes();
}
public function create_settings(){
//Only one instantiation
$frontend = new Frontend_Settings();
$backend = new Backend_Settings;
//.. more like these
}
}
class Frontend_Settings{
public function __construct(){
print_r($name.$version.$slug);
}
}
class Backend_Settings{
public function __construct(){
print_r($name.$version.$slug);
}
}
$firstapp = new application( 'First app', '1.0', 'first-app');
$secondapp = new application( 'Second app', '1.0', 'second-app');
【问题讨论】:
-
这是一个想法——将应用实例化传递给前端和后端设置:
$frontend = new FrontEnd_Settings($this);然后(假设应用具有 getter 函数),前端可以访问应用程序的所有变量:class Frontend_Settings { public function __construct($app) { printf(“%s.%s.%s”, $app->name(), $app->version(), $app->slug() ); }}其中名称() 等都是吸气剂。
标签: php oop inheritance