2017-03-29 63 views
0

我想,一个类实例化时,能够通过它,将用于在类前缀的方法名这样的名称,到目前为止,我有这个类中的动态方法名称?

<?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()的神奇方法,但我不确定这是否可以用在这种情况下,或者如何应用它。

可以这样做吗?

+0

为什么需要这个?像这样使用它是绝对不好的主意。这看起来很糟糕的OOP设计。请描述你的用例。 –

+0

在WordPress中,如果函数中具有'apply_filters'函数,则可以使用过滤器来修改函数的工作方式。我需要能够追加到现有的数组,与所有的插件网址(外观相同,具有不同的导入文件)。为此,我可以手动编写函数并将它们添加到过滤器中,如果有很多这样的插件,这将是漫长而乏味的任务,所以我的想法是创建一个对象来为我做这件事,因为只有函数的前缀名称用于过滤器更改(和数组键) –

回答

1

为什么你不做方法的名称参数?

像这样:

add_filter('my_filter_name', [$this, 'methodName'], 10, 1); 

第三个参数是过滤器的优先级和第四接受ARGS的数目。

public function methodName($name) {} 

,并调用它像这样:

apply_filters('my_filter_name', $value, $arg); 
+0

我会看看这是否可行。在理论上它应该,我之前做过,不知道为什么我一开始就没有使用过它。谢谢 –

+0

否则你可以使用魔术'__call($ name,$ args)'方法,但参数是更好的解决方案。 –

+0

通过一些修改,它可以工作,但是'plugin_dir_path(__FILE__)'总是指向2个插件之一。它注册了两个插件,并且该数组填充了2个很好的数组(名称在数组中正确传递),但路径在两种情况下都是相同的... –

-1

我不是专家,但我认为你必须在构造函数中指定默认版本...我不确定,但你可以试试。

public function __construct($name, $version="1.0.0") { 
     $this->name = $name; 
     $this->version = $version; 
     add_filter('my_filter_name', $name . '_my_folder'); 
    } 
+0

这与这个问题真的没有关系,而且没有必要这样做...... –