Get all method names starting with a substring fro

2020-08-09 05:34发布

I have an object and want a method that returns how much method this Object have that start with bla_.

I found get_class_methods() which returns all method names, but I only want names which starts with bla_

4条回答
我命由我不由天
2楼-- · 2020-08-09 05:49

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 false if no match was found. Due to PHPs dynamic typing this is equal to 0 and therefore a strict (type safe) equality check is needed.

查看更多
欢心
3楼-- · 2020-08-09 05:50

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
查看更多
Deceive 欺骗
4楼-- · 2020-08-09 05:54

You can use preg_grep() to filter them:

$method_names = preg_grep('/^bla_/', get_class_methods($object));
查看更多
走好不送
5楼-- · 2020-08-09 06:05

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?

查看更多
登录 后发表回答