Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 面向对象方法_Php_Oop_Methods - Fatal编程技术网

Php 面向对象方法

Php 面向对象方法,php,oop,methods,Php,Oop,Methods,通常,在许多框架中,可以找到使用查询生成器创建查询的示例。你经常会看到: $query->select('field'); $query->from('entity'); 然而,在某些框架中,您也可以这样做 $object->select('field') ->from('table') ->where( new Object_Evaluate('x') ) ->limit(1) ->or

通常,在许多框架中,可以找到使用查询生成器创建查询的示例。你经常会看到:

$query->select('field');
$query->from('entity');
然而,在某些框架中,您也可以这样做

$object->select('field')
       ->from('table')   
       ->where( new Object_Evaluate('x') )
       ->limit(1) 
       ->order('x', 'ASC');
你实际上是如何制作这种链条的

这被称为--在该页面上有一个

class c
{
  function select(...)
  {
    ...
    return $this;
  }
  function from(...)
  {
    ...
    return $this;
  }
  ...
}

$object = new c;
基本思想是类的每个方法(您希望能够链接)都必须返回
$this
——这使得在返回的
$this
上调用同一类的其他方法成为可能


当然,每个方法都可以访问类的当前实例的属性——这意味着每个方法都可以向当前实例“添加一些信息”。

基本上,您必须使类中的每个方法都返回实例:

<?php

class Object_Evaluate{
    private $x;
    public function __construct($x){
        $this->x = $x;
    }
    public function __toString(){
        return 'condition is ' . $this->x;
    }
}
class Foo{
    public function select($what){
        echo "I'm selecting $what\n";
        return $this;
    }
    public function from($where){
        echo "From $where\n";
        return $this;
    }
    public function where($condition){
        echo "Where $condition\n";
        return $this;
    }
    public function limit($condition){
        echo "Limited by $condition\n";
        return $this;
    }
    public function order($order){
        echo "Order by $order\n";
        return $this;
    }
}

$object = new Foo;

$object->select('something')
       ->from('table')
       ->where( new Object_Evaluate('x') )
       ->limit(1)
       ->order('x');

?>

不客气:-);;是的,每个方法都可以设置/更改属性,“last”方法通常用于“执行”前面调用的任何方法进行配置。不确定使用fluent接口是否会使代码更易于阅读;;;例如,当它用于构建一些SQL查询时,它是有意义的;但是,当这些方法不是真正相关的,也不是那么确定的时候——我想这取决于具体情况;;;很好的一点是,即使您的方法返回
$this
,它们也可以“以一种典型的方式”调用。它是否必须返回
$this
?它不能返回
$that
并从那里继续吗?@PascalMARTIN这样就没有办法触发宿主方法(使用所有方法设置值),而不使用流畅的接口强制转换字符串了吗?用例:
$setup=$Object->add_组件($component_属性)->configure($component_属性)其中Object::add_component()返回它作为$Object属性添加的组件对象(如数组),并使用component::configure()方法对其进行配置。如果没有链接,我们必须确定添加到$Object->Components数组的最后一个元素,然后以这种方式获取Component对象。@AVProgrammer-您的示例没有使用
返回$this
,是吗?是的,Component对象这样做,以允许configure()方法。