Php 类继承情况下的dirname
我有一个父类,它为映像路径保存一个公共变量,并通过类构造函数进行设置Php 类继承情况下的dirname,php,inheritance,dirname,Php,Inheritance,Dirname,我有一个父类,它为映像路径保存一个公共变量,并通过类构造函数进行设置 abstract class Parent_Class { protected $image_path; public function __construct($image_path_base) { $this->image_path = $image_path_base . '/images/'; } } 基本路径取决于子类或其文件位置 class
abstract class Parent_Class {
protected $image_path;
public function __construct($image_path_base) {
$this->image_path = $image_path_base . '/images/';
}
}
基本路径取决于子类或其文件位置
class ChildA_Class {
public function __construct() {
parent::__construct(dirname(__FILE__));
...
}
}
class ChildB_Class {
public function __construct() {
parent::__construct(dirname(__FILE__));
...
}
}
有没有办法消除子类中的
dirname(\uuuu文件)
,并将逻辑移向父类 您想做的事情对我来说似乎很奇怪,但这里有一个可能的解决方案,可以使用反射和后期静态绑定来解决您的问题
abstract class ParentClass
{
protected $imagePath;
public function __construct()
{
// get reflection for the current class
$reflection = new ReflectionClass(get_called_class());
// get the filename where the class was defined
$definitionPath = $reflection->getFileName();
// set the class image path
$this->imagePath = realpath(dirname($definitionPath) . "/images/");
}
}
每个子类都会根据定义子类的位置自动拥有一个图像路径。不要硬编码路径,而是将其作为参数传递给父类::u构造(dirname(u文件).'/images/')在子类中?反射是可能的,但我不推荐它。根据类文件的位置设置映像路径似乎是错误的。你不把代码和其他资源分开吗?嗯,我不太确定。我的代码是一个wordpress插件,这些类用于自定义帖子类型。基类驻留在它自己的文件夹中。然后我有一些不同的“包”,它们在自己的位置使用它。图像路径用于确定post类型图标(基本图标、悬停状态、大图标)的位置。