【问题标题】:Method chaining方法链
【发布时间】:2015-02-21 19:00:41
【问题描述】:
class A {
    public function model($name) {
        if (file_exists($name.'.php')) {
            require $name.'.php';
            $this->$name = new $name();
        }
    }
}
class C extends A {
    function __construct() {
        $this->load = $this;
        $this->load->model('test');
        $this->test->say();
    }
}

$Controller = new C();

我想创建一个简单的代码点火器,比如加载器类。有没有合适的方法来做这项技术?

【问题讨论】:

  • 要使用方法链接,每个方法都必须返回一个对象(通常在方法中使用return $this

标签: php methods chaining


【解决方案1】:

您将使用Fluent Interface 模式。

<?php
class Employee
    {
    public $name;
    public $surName; 
    public $salary;

    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    public function setSurname($surname)
    {
        $this->surName = $surname;

        return $this;
    }

    public function setSalary($salary)
    {
        $this->salary = $salary;

        return $this;
    }

    public function __toString()
    {
        $employeeInfo = 'Name: ' . $this->name . PHP_EOL;
        $employeeInfo .= 'Surname: ' . $this->surName . PHP_EOL;
        $employeeInfo .= 'Salary: ' . $this->salary . PHP_EOL;

        return $employeeInfo;
    }
}

# Create a new instance of the Employee class:
$employee = new Employee();

# Employee Tom Smith has a salary of 100:
echo $employee->setName('Tom')
              ->setSurname('Smith')
              ->setSalary('100');

# Display:
# Name: Tom
# Surname: Smith
# Salary: 100

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多