方法链接 [英] Method chaining
本文介绍了方法链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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();
我想创建一个简单的代码点火器,例如loader类.有没有适当的方法可以做到这一点?
I want to create a simple code igniter like loader class. Is there a proper way for doing this technique?
推荐答案
您将使用 Fluent接口模式.
<?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
这篇关于方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文