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

查看:45
本文介绍了PHP OOP,$this->var->method()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

典型的使用方式:

<?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

我该如何实现:

$obj->var->method();

为什么这很有用?

推荐答案

通过使 var 成为另一个类的对象,您可以将方法调用相互链接.

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'

您可以将它用于依赖注入

此外,它可能使您的代码更具可读性和可理解性,因为您不必在调用它们的方法之前缓冲变量,并且只需在调用它们的方法之后调用一个方法另一个.

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.

看看这个例子:

$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.

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

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

这篇关于PHP OOP,$this->var->method()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆