【发布时间】:2017-03-29 08:20:15
【问题描述】:
我想,在实例化一个类以便能够传递给它一个名称时,该名称将用于为该类中的方法名称添加前缀,到目前为止我有这个
<?php
if ( ! class_exists( 'My_Class' ) ) {
/**
* Creates filter method
*
* @since 1.0.0
*/
class My_Class {
/**
* Prefix for method names
*
* @var string $name Name of the filter prefix.
*/
private $name;
/**
* Version.
*
* @var string
*/
private $version = '1.0.0';
/**
* Initialize the class and set its properties.
*
* @since 1.0.0
* @param string $name The name for the method prefix.
* @param string $version The version of this plugin.
*/
public function __construct( $name, $version ) {
$this->name = $name;
$this->version = $version;
add_filter( 'my_filter_name', $name . '_my_folder' );
}
/**
* Function for filtering folder array
*
* Each plugin has to set its own array of paths and url.
*
* @param array $import_array Array with folder values.
* @return array Modified array with folder values.
*/
public function $name . _my_folder() {
$import_array[$this->name]['folder'] = plugin_dir_path( __FILE__ ) . 'includes/layout';
$import_array[$this->name]['folder_url'] = plugin_dir_url( __FILE__ ) . 'includes/layout';
return $import_array;
}
}
}
我的想法是这样称呼它
$first_object = new My_Class( 'first' );
$second_object = new My_Class( 'second' );
这样我就可以在多个相同的插件中使用它,但名称不同,具体取决于插件的类型。
明显的问题是function $name . _my_folder()。
我读过一些关于 __call() 魔法方法的文章,但我不确定这是否可以在这种情况下使用,或者如何应用它。
这个可以吗?
【问题讨论】:
-
为什么需要这个?像这样使用它绝对是个坏主意。这似乎是糟糕的 OOP 设计。请描述您的用例。
-
在 WordPress 中,如果函数中包含
apply_filters函数,您可以使用过滤器来修改函数的工作方式。我需要能够附加到现有数组,包含所有插件 url 的数组(外观相同的插件,具有不同的导入文件)。为此,我可以手动编写函数并将它们添加到过滤器,如果有很多这样的插件,这是一项漫长而乏味的任务,所以我的想法是创建一个可以为我执行此操作的对象,因为只有函数的前缀名称用于过滤器更改(和数组键)