1

我有这个我在 Wordpress 环境中的主题上创建的课程。

class Theme {
    function __construct()
    {
       add_action('after_setup_theme', array(&$this, 'do_this'));
    }

    function do_this()
    {
       require_once('helper_functions.php');
    }
}
$theme = new Theme();

在 helper_functions.php 我有:

function get_image()
{
    return 'working';
}

但现在我很困惑,因为当我执行这个

echo $theme->get_image();

它不起作用....但是如果我直接调用它,它的工作原理是这样的:

echo get_image();

但是我想既然用的是类方法,就需要用类对象来获取类方法……为什么可以直接调用呢?

4

5 回答 5

0

很明显,你理解错了。get_image()在这种情况下,它不是一种方法。它只是另一个可以在脚本执行期间调用的普通函数。

要使其成为方法,您必须在类声明中声明它。

class Theme 
{
    function __construct()
    {
       add_action('after_setup_theme', array(&$this, 'do_this'));
    }

    function do_this()
    {
       require_once('helper_functions.php');
    }

    function get_image()
    {
        return 'working';
    }
}

在此处阅读有关对象和类的更多信息。

于 2012-04-28T16:13:20.853 回答
0

您不能拆分类定义。所有这些都需要一口气完成。如果你的班级太大,也许它有太多的责任。

  • 将业务逻辑与工厂逻辑分开(工厂逻辑是实例化新对象的逻辑,业务逻辑那些对象)。
  • 按功能分隔类。
  • 使用继承和多态。

当您在函数中包含文件时,它只存在于该函数的范围内。这意味着您所做的相当于:

public function do_this() {
    function get_image() { ... }
}

这并没有真正做任何事情。

于 2012-04-28T17:17:02.647 回答
0

include 和 require 通常被称为“就像将文件内容复制/粘贴”到父脚本中,这似乎是您所期待的。但是,它并不真正正确,这就是为什么你正在做的事情不起作用。

某些语言具有编译器宏,可以在解释代码之前进行文本替换,这样就可以了。但是,php 没有,并且所有包含语句都在运行时进行评估。在您的情况下,该类在执行该 require 语句之前已完全定义。结果,您只是在执行代码,它定义了一个全局函数。

于 2012-04-28T16:20:34.280 回答
0

该函数get_image()不是类中设置的函数Theme,它设置在单独的文件中,该文件包含在类中。

如果你想让它成为类的函数,那么你需要将它写在类文件中,将代码移动到类中。

替代你可以利用类扩展

class Helper_functions  {

    public function get_image() {
        return "working!";
    }
}

并将主题类文件更改为

class Theme extends Helper_functions {

    function __construct()
    {
       add_action('after_setup_theme', array(&$this, 'get_image'));
    }

}

$theme = new Theme();

替代方案
由于您说它是多个文件中的多个函数,您可以在主题类文件或扩展类文件中执行此操作。

class Theme {

    ...

    function get_image() { include('theme_file_get_image.php'); }
    function another_function { include('theme_file_another_function.php'); }
}
于 2012-04-28T16:18:07.633 回答
0

这个问题的答案总结了您在此处看到的结果:

“包含文件中的代码与函数在同一范围内执行(定义的函数和类是全局的),而不是插入其中,替换那里的其他代码。”

所以包含文件中的函数是在全局范围内定义的,这就是调用的原因get_image()

这应该等同于:

//Include the helper functions
require_once('helper_functions.php');

class Theme 
{
    function __construct()
    {
       add_action('after_setup_theme', array(&$this, 'do_this'));
    }

    function do_this()
    {
       get_image();
    }
}

$test = new Theme();
echo $test->do_this(); //'working';

请注意,get_image() 位于全局分数中,而不是Theme 类的成员函数。

于 2012-04-28T16:18:23.730 回答