从 PHP 对象中获取以子字符串开头的所有方法名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1826503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all method names starting with a substring from a PHP object
提问by gustavgans
I have an object and want a method that returns how much method this Object have that start with bla_.
我有一个对象并且想要一个方法来返回这个对象有多少方法以bla_.
I found get_class_methods()which returns all method names, but I only want names which starts with bla_
我发现get_class_methods()它返回所有方法名称,但我只想要以开头的名称bla_
回答by soulmerge
You can use preg_grep()to filter them:
您可以使用preg_grep()过滤它们:
$method_names = preg_grep('/^bla_/', get_class_methods($object));
回答by Emil H
Try:
尝试:
$methods = array();
foreach (get_class_methods($myObj) as $method) {
if (strpos($method, "bla_") === 0) {
$methods[] = $method;
}
}
Note that ===is necessary here. ==won't work, since strpos()returns falseif no match was found. Due to PHPs dynamic typing this is equal to 0and therefore a strict (type safe) equality check is needed.
注意===这里是必要的。==将不起作用,因为如果找不到匹配项,则strpos()返回false。由于 PHP 的动态类型,这等于0,因此需要严格(类型安全)相等性检查。
回答by Samuel
Why don't you just make your own function that loops through the array from get_class_methods() and tests each element against "bla_" and returns a new list with each matching value?
为什么不创建自己的函数,循环遍历 get_class_methods() 中的数组并针对“bla_”测试每个元素并返回一个具有每个匹配值的新列表?
回答by Kevin
I would suggest something a bit more flexible such as this (unless the method names are dynamic or are unknown):
我会建议一些更灵活的东西,比如这样(除非方法名称是动态的或未知的):
interface ITest
{
function blah_test();
function blah_test2();
}
class Class1 implements ITest
{
function blah_test()
{
}
function blah_test2()
{
}
function somethingelse()
{
}
}
$obj = new Class1();
$methods = array_intersect( get_class_methods($obj), get_class_methods('ITest') );
foreach( $methods as $methodName )
{
echo "$methodName\n";
}
Outputs:
输出:
blah_test
blah_test2

