php 根据字符串生成数组中,PHP – 从字符串数组生成函数

本文探讨如何使用PHP的__call()魔术方法,通过传入的变量名动态创建getter和setter方法,简化属性操作,减少重复代码。方法涉及匹配名称格式,验证方法存在,并调用相关函数或EntityValue方法。
摘要由CSDN通过智能技术生成

在我的应用程序中,我需要许多getter和setter,我的想法是从数组中生成它们,例如:

protected $methods = ['name', 'city'];

有了这两个参数,我需要生成以下方法:

public function getNameAttribute() {

return $this->getName();

}

public function getName($lang = null) {

return $this->getEntityValue('name', $lang);

}

对于城市,方法将是:

public function getCityAttribute() {

return $this->getCity();

}

public function getCity($lang = null) {

return $this->getEntityValue('city', $lang);

}

当然,我也需要生成setter(使用相同的逻辑).

正如您所看到的,我将需要一个带有< variable_name>属性的方法,并在此调用中获取< variable_name>而另一个(getName)甚至返回相同的方法(对于每个getter),只需更改’name’参数即可.

每个方法都有相同的逻辑,我想“动态”生成它们.我不知道这是否可能..

最佳答案 您可以使用

__call()来执行此操作.我不打算提供完整的实现,但你基本上想做的事情如下:

public function __call($name, $args) {

// Match the name from the format "getAttribute" and extract .

// Assert that is in the $methods array.

// Use to call a function like $this->{'get' . $name}().

// 2nd Alternative:

// Match the name from the format "get" and extract .

// Assert that is in the $methods array.

// Use to call a function like $this->getEntityValue($name, $args[0]);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值