Pergunta

For example record like this: property3->property2->property1 is understood for me, this means that property of class, is object of another class, for example:

class a {
        public $property1 = "some";
}


class b {
    function __construct () {
        $this->property2 = new a();
    }           
}

$obj = new b();
echo $obj->property2->property1;

this understood. but I can not understood records like this: method1()->method2()->method3()

can you post simple example, who using these records?

Foi útil?

Solução

A simple example :

class A {

  function fooA() {
    echo "a...";
    return $this;
  }

  function fooB() {
    echo "b...";
    return $this;
  }

  function fooC() {
   echo "c...";
  }
}

$a = new A();
$a->fooA()->fooB()->fooC();

Or with several classes :

class A
{
  private $b;

  public function __construct()
  {
    $this->b = new B();
  }

  public function fooA()
  {
    echo "A...";
    return $this->b;
  }

}

class B
{

  public function fooB()
  {
    echo "B...";
  }

}

$a = new A();
$a->fooA()->fooB();

Outras dicas

It means that these functions return objects. For example, the following is possible (assuming $pdo is a valid PDO object):

$result = $pdo->query("SELECT * FROM `table`")->fetchAll();

This may not always be favorable, because you:

  1. Lose readabiliy.
  2. Lose the ability to use the objects in between.
  3. Lose the ability to check for errors, and you are counting on the methods to return what you think it is.

    In this example, you only get the resultset in the form of an array, but you cannot access PDOStatement which is returned by PDO::query(). In this case, it may not matter, in some cases it might.

    Also, PDO::query() may return a BOOLEAN false in the case of an error, which would give an unexplained "Method fetchAll() used on an non-object" error.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top