2017-04-06 77 views
0

我是面向对象编程的新手。
我的问题是,我在类方法中包含一个文件。
现在我怎么能在所需的文件内使用类方法?我用$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> 

回答

0

你可以从这个类和调用方法来创建对象

$c = new Test; 
$c->two(); 
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)制作更复杂的东西。

0

你应该看看性状:

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

比方说您做traitTest.php;像这样

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

然后你可以包括这beofre声明您的类,并使用“使用”关键字:

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(); 

可以使用使许多类一个或多个特征;

0

基本上,你正在做的是将'file.php'的内容包含到'Main.php'方法一()中。最终结果是,在调用此方法时,将读取'file.php'的内容,并调用方法2()。在OOP中,你应该避免这种耦合和依赖(在不同的文件中),你应该强制封装。

最重要的是组织您的代码,以避免您的操作,如果不可能,然后评论代码。