如何获得非继承的PHP类方法


How to get non inherited PHP class methods?

我想获得非继承的子类公共方法。我试着这样使用反射Api:

$class = new 'ReflectionClass($model);
$modelMethods = $class->getMethods('ReflectionMethod::IS_PUBLIC);
$exclude = ['getSource', 'upsert', 'getUniqueKeyAttributes', 'beforeSave', 'columnMap', 'initialize', 'setId', 'getId'];
$CLASS = __CLASS__;
$props = array_filter(array_map(function('ReflectionMethod $method) use ($exclude, $CLASS) {
    if($method->class === $CLASS && !in_array($method->name, $exclude)) {
        if(strpos($method->name, 'get') === 0) {
            return str_replace('get', '', $method->name);
        }
    }
}, $props));

但这就产生了很多多余的逻辑。我必须自动获得所有的getter或setter,因为我得到了60多个!

1。坚持现有解决方案

我只想用array_map替换array_filter,以获得更高效的内部过滤。当您100%控制函数参数时,声明函数参数的类型是不必要的,但会降低PHP的速度。此外,substr()应该比str_replace()出现得更快。

让我支持一个完全相同但不同的代码的简短示例:

    $class = 'Application'Entity'ExamplePhalconModel';
    // ure filtering those with "get" only
    $exclude = array_flip(['getSource', 'getId']);
    
    $result = array_map(function($v) { return substr($v->name, 3); } , array_filter((new 'ReflectionClass($class))->getMethods('ReflectionMethod::IS_PUBLIC), function ($v) use ($class, $exclude) {
        return (strpos($v->name, 'get') === 0 && $v->class === $class) && !array_key_exists($v->name, $exclude);
    }));

分解,首先我创建了一个类的反射,该类与您所做的一样使用(new 'ReflectionClass($class))->getMethods('ReflectionMethod::IS_PUBLIC)进行检查。将其作为array_filter()的第一个参数可以让我提交一些变量声明。作为第二个参数,函数中只有一个if

function ($v) use ($class, $exclude) {
    return (strpos($v->name, 'get') === 0 && $v->class === $class) && !array_key_exists($v->name, $exclude);
}

用于检查是否以"0"开头;得到";总之,如果它在正确的类中,最后,如果它不在排除的方法名中。

最后,整个array_filter()结果转移到array_map(),只是为了将它们从对象变形为不包含"0"的字符串;得到";单词


PS:主要是进一步的优化和混淆;)

2.Phalcon模型::columnMap

或者只是:

$props = array_map(function($str) {
        return 'Phalcon'Text::camelize($str);
    }, array_values(Application'Entity'ExamplePhalconModel::columnMap()));

但您可能需要筛选出一个"Id"字段;