如何动态调用以给定前缀开头的所有实例方法?



>我有一个类,我想动态调用所有以默认名称开头的函数:

class social_button
{
public function __construct()
{
[...]
}
private function social_facebook()
{[...]}
private function social_instagramm();
{[...]}
private function social_twitter();
{[...]}
[and so on]
}

我的问题是,我不会一直写:

$this->social_facebook();
$this->social_twitter();
...

因为它可能/将是一个无穷无尽的列表。

所以这是我的问题:

有没有办法从"社交"开始调用所有函数泛型/动态? 喜欢:$this->social_*();

("*"类似于占位符,其中包含无限数量的字符(

对不起,我的英语不好,非常感谢所有的回答。

此致敬意

您可以使用字符串连接构建方法名称:

$service = 'facebook';
$this->{'social_' . $service}();

$service = 'social_facebook';
$this->$service();

如果您想呼叫所有这些,请使用:

$services = ['facebook', 'twitter'];
foreach ($services as $service) {
$this->{'social_' . $service}();
}

编辑:请参阅下面的localheinz的答案,以获取更好的方法,使用反射。get_class_methods()只会返回公共方法。


基于hsz的回答:

您可以使用get_class_methods()获取类方法的列表。然后,您可以遍历结果,如果该方法以"social_"开头,则调用该方法。

// Get the list of methods
$class_methods = get_class_methods("social_button");
// Loop through the list of method names
foreach ($class_methods as $method_name)
{
// Are the first 7 characters "social_"?
if (substr($method_name, 0, 7) == "social_")
{
// Call the method
$this->{$method_name}();
}
}

接受答案的问题在于它不适用于与问题一起发布的示例。get_class_methods()仅返回public方法,但有问题的方法标记为private

如果要确定所有方法,请改用反射:

class social_button
{
private function social_facebook()
{
return 'Facebook';
}
private function social_instagram()
{
return 'Instagram';
}
private function social_twitter()
{
return 'Twitter';
}
public function all()
{
$reflection = new ReflectionObject($this);
$prefix = 'social_';
// filter out methods which do not start with the given prefix
$methods = array_filter($reflection->getMethods(), function (ReflectionMethod $method) use ($prefix) {
return 0 === strpos($method->getName(), $prefix);
});
// invoke all methods and collect the results in an array
$results = array_map(function (ReflectionMethod $method) {
$name = $method->getName();
return $this->$name();
}, $methods);
return $results;
}
}
$button = new social_button();
var_dump($button->all());

有关参考,请参阅:

  • http://php.net/manual/en/class.reflectionobject.php
  • http://php.net/manual/en/class.reflectionmethod.php
  • http://php.net/manual/en/function.array-filter.php
  • http://php.net/manual/en/function.array-map.php

有关示例,请参阅:

  • https://3v4l.org/qTkOM

最新更新