PHP OOP, $this->var->method()? [closed]

2019-09-02 05:06发布

问题:

The typical way to use :

<?php

class A {
  public $var;

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

  public function do_print(){
    print $this->var;
  }
}

?>

$obj = new A('Test');
$obj->do_print(); // Test

How can I implement something like:

$obj->var->method();

And why is this useful?

回答1:

By making var an object of another class, you can chain the method calls to one another.

<?php
    class Foo {
        public $bar;
        public function __construct(Bar $bar) {
            $this->bar= $bar;
        }
    }

    class Bar {
        private $name;
        public function __construct($name) {
            $this->name = $name;
        }
        public function printName() {
            echo $this->name;
        }
    }

    $bar = new Bar('Bar');
    $bar2 = new Bar('Bar2');
    $foo = new Foo($bar);

    $foo->bar->printName(); // Will print 'Bar';
    $bar2->printName(); // Will print 'Bar2'

You can use this for neat things like Dependency Injection

Also, it may make your code bette readable and understandable because you don't have to buffer variables before making calls to their methods and can just call one method after the other.

Look at this example:

$obj = new MyObject();
$db = $obj->getDb();
$con = $db->getCon();
$stat = $con->getStat();

Which could be written like this using method chaining:

$obj = new Object();
$stat = $obj->getDB()->getCon()->getStat();

But, this is also harder to debug because if any of these methods throw an exception, you will just get the line number where the chain is, which can be quite a hazzle.

So, there are always two sides. It's just another style of programming.

Just be sure not to chain too long in a single line, as you will definitely lose overview.

BAD

$obj->meth('1', $arg2, array('arg2'))->method2($whaterver, array('text' => $bla_text))->andSoOn();

GOOD

$obj->meth('1', $arg2, array('arg2'))
    ->method2($whaterver, array('text' => $bla_text))
    ->andSoOn();


回答2:

Your class could be something complicated, like a person that has an adress ( just like another class company could have one). Adress is a class in itself, so you'd want to call

$person->adress->makeLabel();

or

$company->adress->makeLabel():

You can implement this by making an object in your person (or company) class, just like a var:

Class Person{
  public $address;

  public function __construct(){
    $this->address = new address();

  }
 }


标签: php oop