【问题标题】:PHP include class in other classPHP在其他类中包含类
【发布时间】:2013-04-23 16:57:22
【问题描述】:

我正在学习 OOP,并且非常困惑于彼此使用类。

我总共有 3 节课

//CMS System class
class cont_output extends cont_stacks
{
    //all methods to render the output
}


//CMS System class
class process
{
    //all process with system and db
}


// My own class to extends the system like plugin
class template_functions
{
    //here I am using all template functions
    //where some of used db query
}

现在我想在两个系统类中使用我自己的类 template_functions。但是很迷茫怎么用。请帮助我理解这一点。

编辑: 对不起,我忘了在不同的 PHP 文件中提到我自己的类。

【问题讨论】:

  • 我很困惑你的困惑是什么......
  • 听起来你想要多重继承,以便 cont_output 扩展 cont_stacks 和 template_functions?因为否则,没有理由 #1 类不能调用静态方法,或者在自身内部实例化类 #2 的副本。
  • @MarcB 这有点像,但取决于我如何在两个类中使用我自己的类。

标签: php oop class include


【解决方案1】:

首先,请确保您在使用之前include 类文件:

include_once 'path/to/tpl_functions.php';

这应该在您的 index.php 中或在使用 tpl_function 的类的顶部完成。还要注意autoloading 类的可能性:

从 PHP5 开始,您必须能够自动加载类。这意味着您注册了一个钩子函数,每次尝试使用尚未包含代码文件的类时都会调用该函数。这样做你不需要在每个类文件中都有include_once 语句。举个例子:

index.php 或任何应用程序入口点:

spl_autoload_register('autoloader');

function autoloader($classname) {
    include_once 'path/to/class.files/' . $classname . '.php';
}

从现在开始,您可以访问这些类,而不必再担心包含代码文件了。试试看:

$process = new process();

了解这一点后,您可以通过多种方式使用 template_functions


只需使用它

如果您创建一个实例,您可以在代码的任何部分访问该类:

class process
{
    //all process with system and db

    public function doSomethging() {
        // create instance and use it
        $tplFunctions = new template_functions();
        $tplFunctions->doSomethingElse();
    }
}

实例成员:

以流程类为例。为了使 process 类中的 template_functions 可用,您创建一个实例成员并在需要它的地方初始化它,构造函数似乎是一个好地方:

//CMS System class
class process
{
    //all process with system and db

    // declare instance var
    protected tplFunctions;

    public function __construct() {
        $this->tplFunctions = new template_functions;
    }

    // use the member : 

    public function doSomething() {
        $this->tplFunctions->doSomething();
    }


    public function doSomethingElse() {
        $this->tplFunctions->doSomethingElse();
    }
}

【讨论】:

  • 感谢您的快速回复.. 只是几个查询.. protected 是一个变量,所以它需要$ 吗?我忘了在单独的 php 文件中提到我的类
  • 那么在哪里包含我的文件?
  • 我将举一个自动加载的例子。给我几分钟。你应该知道这...
  • 好的。无论如何,您都应该阅读有关自动加载的信息,因为它是 php 的一个cool 功能! :)
  • 当然!我会这样做..我真的需要了解所有这些..非常感谢
【解决方案2】:

你可以扩展template_functions类,然后你就可以使用所有的功能了。

class cont_output extends cont_stacks //cont_stacks has to extend template_functions
{
    public function test() {
        $this->render();
    }
}


class process extends template_functions
{ 
    public function test() {
        $this->render();
    }
}


class template_functions
{
    public function render() {
        echo "Works!";
    }
}

【讨论】:

  • 但是class process 呢?对不起,但试图理解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多