Skip to main content
 首页 » 编程设计

php中是否可以在 PHP 中编写一系列重复引用单个对象的语句

2025年01月19日82birdshome

是否可以编写一系列重复引用单个对象的语句,而不必每次都写入该对象?

我之所以这样做是因为我以前在 Visual Basic 中这样做过:

With person 
    .setFullName(.firstName+" "+.lastName) 
    .addParent(parent) 
    .save() 
End With 

这是一个简写

person.setFullName(person.firstName+" "+person.lastName) 
person.addParent(parent) 
person.save() 

可以用 PHP 实现这一点吗? 重写下面的代码而不需要写 $person 5 次?

$person->setFullName($person->firstName.' '.$person->lastName); 
$person->addParent($parent); 
$person->save(); 

注意:我不是指方法链接,原因有两个:

1) 我也想使用公共(public)成员

2) 我不使用我编写的类,因此无法将 return $this; 添加到所有方法

谢谢

请您参考如下方法:

存在允许执行此操作的 PHP 库: https://github.com/lisachenko/go-aop-php

实现示例: http://go.aopphp.com/blog/2013/03/19/implementing-fluent-interface-pattern-in-php/

创造你的方面

<?php 
use Go\Aop\Aspect; 
use Go\Aop\Intercept\MethodInvocation; 
use Go\Lang\Annotation\Around; 
 
class FluentInterfaceAspect implements Aspect 
{ 
    /** 
     * Fluent interface advice 
     * 
     * @Around("within(FluentInterface+) && execution(public **->set*(*))") 
     * 
     * @param MethodInvocation $invocation 
     * @return mixed|null|object 
     */ 
    protected function aroundMethodExecution(MethodInvocation $invocation) 
    { 
        $result = $invocation->proceed(); 
        return $result!==null ? $result : $invocation->getThis(); 
    } 
} 

添加匹配接口(interface)

interface FluentInterface 
{ 
 
} 
 
 
class User implements FluentInterface 
{ 
    protected $name; 
    protected $surname; 
    protected $password; 
 
    public function setName($name) 
    { 
        $this->name = $name; 
    } 
 
    public function setSurname($surname) 
    { 
        $this->surname = $surname; 
    } 
 
    public function setPassword($password) 
    { 
        if (!$password) { 
            throw new InvalidArgumentException("Password shouldn't be empty"); 
        } 
        $this->password = $password; 
    } 
} 

使用

$user = new User; 
$user->setName('John')->setSurname('Doe')->setPassword('root'); 

但是您可以编写匹配规则而无需添加新接口(interface)。

附注这不是问题的正确答案,因为需要其他语法糖。 PHP 不支持此类语法。