Method chaining

柔情痞子 提交于 2019-12-10 12:18:32

问题


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();

I want to create a simple code igniter like loader class. Is there a proper way for doing this technique?


回答1:


You would use Fluent Interface pattern.

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


来源:https://stackoverflow.com/questions/28650010/method-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!