【发布时间】:2017-11-30 11:29:34
【问题描述】:
我需要您的指导,这可能是一个非常基本的问题,但即使经过大量谷歌搜索,我也无法弄清楚这一点。我可以通过 Eureka 类访问其他类的变量,但不能访问它们的函数。
这是我的情况:
index.php 中的类自动加载函数
<?php
function __autoload($class_name)
{
//$class_name = strtolower($class_name);
$path = "{$class_name}.php";
if (file_exists($path)) {
include ($path);
} else {
die("{$path} file could not be found!<br />");
}
}
?>
基类,我想在html页面上使用这个类的对象访问所有其他类:
<?php
class Eureka
{
public $some_var1;
public function get_all_settings()
{
echo 'get_all_settings was called from Eureka class.';
}
}
?>
timezone.php 中的时区类
<?php
class TimeZone
{
public $some_var2;
public function get_time_zone()
{
echo 'get_time_zone was called from TimeZone class.';
}
}
?>
location.php 中的位置类
<?php
class Location
{
public $some_var3;
public function set_location($location_name)
{
echo 'set_location was called from Location class.';
}
}
?>
html页面索引.php
<?php
$eureka = new Eureka;
//**How can I achieve this ????**
$eureka->TimeZone->get_time_zone();
//**OR**
$eureka->Location->set_location('some_location_name');
?>
例如当 $eureka 对象调用 'TimeZone' 类时,它应该被加载并调用 'get_time_zone()' 方法没有任何错误。
【问题讨论】:
-
修改 Eureka 类的构造函数,创建新的 TimeZone 和 Location 实例,并将它们存储为属性......
public function __construct() { $this->TimeZone = new TimeZone(); $this->Location = new Location(); } -
这不是它的工作方式,也不是依赖注入。你可以实现__get 来做到这一点,但这完全是错误的。
-
或者你可以使用魔术
__get()方法 -
但是像你描述你的“Eureka”类的“God Class”是非常糟糕的编码实践
-
@MarkBaker 我不一定会这么说,CI 是一个“神”类。这取决于它在功能上是否适合应用程序或惰性。让我告诉你我是一个懒惰的程序员。但是我建造东西是为了为我建造东西,这就是我的懒惰。
标签: php oop dependency-injection