【问题标题】:how to change a class method behavior and output in php如何在 php 中更改类方法的行为和输出
【发布时间】:2016-04-21 22:49:06
【问题描述】:

如何设计一个可以影响类的调用方法并从中获取输出的模式,例如当我们使用return $this 时,我们可以使用指针不断调用多个方法,但是在这种方法中,我们不能影响前面的方法通过最后调用的方法调用方法..

实例代码:

layout1.php
|--------------|
<div>

 {content}

</div>


index.php 
|-----------|

//return output
$view->layout('layout1')->content('test');

万一实例代码改为如下

//echo output
$view->layout('layout1');

我需要通知该函数并在发送输出时显示不同的行为。例如,在第一个代码中应该返回输出值,但在第二个代码中,必须直接回显该值..

示例代码:

layout1.php
|--------------|
<div>

{content}

</div>


index.php 
|-----------|

$view = view();

//return output
$view->layout('layout1')->content('test');


//echo output
$view->layout('layout1');



 view.php
|-----------|

class view{

 public function layout($file){

  return $this;
 }


 public function content($html){

 return $this;
 }

}

非常感谢您的帮助...

【问题讨论】:

    标签: php oop design-patterns frameworks template-engine


    【解决方案1】:

    嗨,实际上不可能改变链式调用规则。 你能做的就是改变方法

    $view->content('test')->layout('layout1');
    

    你的问题解决了:)

    class view{
    
     public function layout($file){
    
      return $this;
     }
    
    
     public function content($html){
    
     return $this;
     }
    public function __toString(){
    return $vars; // in a string format
    }
    

    echo $view->layout('layout1'); // will echo the result
    $view->layout('layout1')->content('test'); // return result
    

    }

    【讨论】:

    • 如何返回$view->layout('layout1');变量?
    猜你喜欢
    • 2010-09-14
    • 1970-01-01
    • 2021-04-10
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多