在类的包含文件中使用类方法

时间:2017-04-06 10:18:05

标签: php oop

我是面向对象编程的新手 我的问题是,我在类方法中包含了一个文件 现在我如何在所需文件中使用类方法?我使用$this->two()并且它工作正常,但我不认为这是最好的方法。如果其他人正在阅读代码,他将很难理解代码。
对此有何选择?

//Main.php 
class Test{

    public function one(){
        ....
        require('file.php');
    }

    public function two(){
        ....
    }

    public function three(){
        ....
    }
}
?>

//file.php
<div>
    <?php $this->two(); ?>
</div>

4 个答案:

答案 0 :(得分:0)

您可以从此类创建对象并调用方法

$c = new Test;
$c->two(); 

答案 1 :(得分:0)

将此文件用作真实模板

//Main.php 
class Test{

public function one(){
    ....
    print str_replace('{two}',$this->two(),file_get_contents('file.php'));
}

public function two(){
    ....
}

public function three(){
    ....
}
}
?>

//file.php
<div>
   {two}
</div>

你应该阅读更多关于MVC和模板引擎(比如smarty)来制作更复杂的内容。

答案 2 :(得分:0)

您应该研究特征:

http://php.net/manual/en/language.oop5.traits.php

假设你制作了traitTest.php;

trait traitTest{
  function foo(){
    echo "foo";
  }
}

然后你可以包含这个声明你的类并使用'use'关键字,如下所示:

require_once traitTest.php; //need to be 'loaded' before you declare class

    class test{
      use traitTest;

      function bar(){
      echo 'bar';
     }
    }

然后你可以这样做:

$test=new test();
$test->foo();
$test->bar();

您可以使用一个或多个特征制作许多课程;

答案 3 :(得分:0)

基本上,您正在做的事情包括&#39; file.php&#39;进入&#39; Main.php&#39;方法一()。最终结果是,在调用此方法时,&#39; file.php&#39;读取并调用方法二()。在OOP中,你应该避免这种耦合和依赖(在不同的文件中),你应该强制封装。

最重要的是构建代码以避免执行操作,如果不可能,则对代码进行注释。