Php 类中的动态方法名称?
我想,当实例化一个类,以便能够向它传递一个名称,该名称将用于在该类中作为方法名称的前缀时,到目前为止,我有以下内容Php 类中的动态方法名称?,php,wordpress,oop,methods,Php,Wordpress,Oop,Methods,我想,当实例化一个类,以便能够向它传递一个名称,该名称将用于在该类中作为方法名称的前缀时,到目前为止,我有以下内容 <?php if ( ! class_exists( 'My_Class' ) ) { /** * Creates filter method * * @since 1.0.0 */ class My_Class { /** * Prefix for method names
<?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;
}
}
}
这样我就可以在多个相同的插件中使用它,根据插件的类型使用不同的名称
明显的问题是函数$name_我的文件夹()
我读了一些关于\u call()
魔术方法的文章,但我不确定这是否可以用于这种情况,或者如何应用它
这可以做到吗?我不是专家,但我认为您必须在构造函数中指定默认版本。。。我不确定,但你可以试试
public function __construct( $name, $version="1.0.0" ) {
$this->name = $name;
$this->version = $version;
add_filter( 'my_filter_name', $name . '_my_folder' );
}
为什么不将方法的名称参数设置为 像这样:
add_filter('my_filter_name', [$this, 'methodName'], 10, 1);
第三个参数是过滤器的优先级,第四个参数是接受参数的数量
public function methodName($name) {}
这样称呼它:
apply_filters('my_filter_name', $value, $arg);
你为什么需要这个?像这样使用它绝对是个坏主意。这似乎是糟糕的OOP设计。请描述您的使用案例。在WordPress中,如果函数中有
apply\u filters
功能,您可以使用过滤器修改函数的工作方式。我需要能够附加到现有的数组,数组与所有的插件URL(外观相同的插件,不同的导入文件)。为此,我可以手动编写函数并将它们添加到过滤器中,如果有许多这样的插件,这将是一项漫长而乏味的任务,因此我的想法是创建一个对象来为我完成这项工作,因为只有用于过滤器更改(和数组键)的函数的前缀名,我才知道这是否可行。理论上应该是这样的,我以前做过,不知道为什么我一开始没有用过。感谢您可以使用magic\uu call($name,$args)
方法,但参数是更好的解决方案。经过一些修改,这是可行的,但是插件目录路径(\uu文件\uuu)
始终指向两个插件中的一个。它注册了两个插件,数组中填充了两个非常棒的数组(数组中正确传递了名称),但两种情况下的路径都是相同的…这很有意义,因为我在第一个插件中定义了类,所以它用于在第二种情况下创建具有相同dir路径的实例。。。我还得加上这个作为论点。我很笨,请将文件路径作为下一个参数传递
apply_filters('my_filter_name', $value, $arg);