什么是更好的方式来引用实例化对象的方法?

时间:2015-08-04 23:38:20

标签: php class methods reference instance

好的,所以我已经创建了一个简单的重新创建我遇到的问题并且我已经测试了代码并且它运行了。我的问题是,当摇滚的一个实例在一个纸张实例中而不将实例化对象注入每个方法时,如何从Rock-> mb()中调用Paper-> important()?我通过传递/将my this of mypaper注入rock的方法来完成它。主要问题是只有一种摇滚方法需要它,所以我怎样才能轻松访问实例化对象的方法而不将它们传递给每个函数,考虑到我运行了很多功能?最后一个问题是,或许甚至重要我已将它们注入到每个方法中,它会使用额外的内存还是资源? 我应该通过引用传递$ this吗?,它会节省内存吗?另外,当我传递未使用的额外参数时会发生什么?

<?php
class Rock{
    public function ma($args){ //what happens when it gets injected into this function?
        return $args." in ma";
    }
    public function mb($args,$context){ //do I have to inject it?
        if($args=="args2"){
            $context->important();
            return "<br>".$args." in mb";
        }
    }
    //50 other functions that DONT require paper->important()
}

class Paper{

    public function __construct($vitalString){
        $this->vitalString = $vitalString;
    }
    public function all(){
        $list = ['ma'=>'args1','mb'=>'args2'];
        $objRock = new Rock();
        foreach($list as $meth=>$args){
            if(method_exists($objRock,$meth)){
                $response = $objRock->{$meth}($args,$this);
                //can I avoid injecting the instantiating $this, into every function I call if only one needs it?
                echo $response;
            }
        }
    }
    function important(){
        echo "<br>".$this->vitalString;
    }
}

$myPaper = new Paper("Super Duper");

$myPaper->all();
?>

这是输出

  

马的args1   Super Duper
  args2 in mb

1 个答案:

答案 0 :(得分:0)

我会像你现在那样进行构造函数注入而不是方法注入,见下文:

class Rock{
    private $paper;

    public function __construct($paper){
        $this->paper = $paper;
    }

    public function ma($args){ 
        return $args." in ma";
    }


    public function mb($args){ //do I have to inject it?
        if($args=="args2"){

            $this->paper->important();

            return "<br>".$args." in mb";
        }
    }
    //50 other functions that DONT require paper->important()
}

在mb方法中,我从

更改了你的电话
$context->important();

$this->paper->important();

论文课程现在如下所示:

class Paper{

    public function __construct($vitalString){
        $this->vitalString = $vitalString;
    }
    public function all(){
        $list = ['ma'=>'args1','mb'=>'args2'];

        $objRock = new Rock($this); //<-------------------

        foreach($list as $meth=>$args){
            if(method_exists($objRock,$meth)){

                $response = $objRock->{$meth}($args); //<-----------------

                //can I avoid injecting the instantiating $this, into every function I call if only one needs it?
                echo $response;
            }
        }
    }
    function important(){
        echo "<br>".$this->vitalString;
    }
}

使用构造函数注入,您可以在任何地方使用注入的类,而不必担心将其传递到每个方法,即使方法不需要它。 (另外,使用从未使用的参数的函数会让人感到困惑。)除非纸质类具有大量具有天文数据量的属性,否则您不必担心内存问题。

构造函数注入方法也很方便,以防您决定添加需要使用纸质类的其他方法 - 如果您需要它,它就在那里。

顺便说一句,所有对象都是通过引用自动传递的 - 但这不是构造函数注入方法的关注点。

相关问题