错误的静态方法

Bab*_*aba 15 php static

PHP 调用父类中的私有方法,而不是调用当前类中的方法 call_user_func

class Car {
    public function run() {
        return call_user_func(array('Toyota','getName')); // should call toyota
    }
    private static function getName() {
        return 'Car';
    }
}

class Toyota extends Car {
    public static function getName() {
        return 'Toyota';
    }
}

$car = new Car();
echo $car->run(); //Car instead of Toyota

$toyota = new Toyota();
echo $toyota->run(); //Car instead of Toyota
Run Code Online (Sandbox Code Playgroud)

Mri*_*hal 6

我找到了一种采用不同方法的解决方案..

<?php
 class Car {
    public static function run() {
     return static::getName();
   }
   private static function getName() {
    return 'Car';
    }
  }

   class Toyota extends Car {
     public static function getName() {
        return 'Toyota';
      }
   }
echo Car::run();
echo Toyota::run();
  ?>
Run Code Online (Sandbox Code Playgroud)

使用Late Static Binding..


Dav*_*dom 1

这是一个似乎在很长一段时间内波动存在和不存在的错误(请参阅@deceze 在该问题的评论中的测试)。可以使用反射“修复”此问题 - 即在 PHP 版本之间提供一致的行为:

由于依赖于ReflectionMethod::setAccessible()调用私有/受保护的方法,因此适用于 PHP 5.3.2 及更高版本。我将很快对此代码添加进一步的解释,它能做什么、不能做什么以及它是如何工作的。

不幸的是,无法直接在 3v4l.org 上测试它,因为代码太大,但是这是缩小PHP 代码的第一个真正的用例 - 如果您这样做,它确实可以在 3v4l 上工作,所以请随意尝试并看看你能不能打破它。我知道的唯一问题是它目前无法理解parent。它还受到$this5.4 之前缺乏闭包支持的限制,但实际上对此无能为力。

<?php

function call_user_func_fixed()
{
    $args = func_get_args();
    $callable = array_shift($args);
    return call_user_func_array_fixed($callable, $args);
}

function call_user_func_array_fixed($callable, $args)
{
    $isStaticMethod = false;
    $expr = '/^([a-z_\x7f-\xff][\w\x7f-\xff]*)::([a-z_\x7f-\xff][\w\x7f-\xff]*)$/i';

    // Extract the callable normalized to an array if it looks like a method call
    if (is_string($callable) && preg_match($expr, $callable, $matches)) {
        $func = array($matches[1], $matches[2]);
    } else if (is_array($callable)
                   && count($callable) === 2
                   && isset($callable[0], $callable[1])
                   && (is_string($callable[0]) || is_object($callable[0]))
                   && is_string($callable[1])) {
        $func = $callable;
    }

    // If we're not interested in it use the regular mechanism
    if (!isset($func)) {
        return call_user_func_array($func, $args);
    }

    $backtrace = debug_backtrace(); // passing args here is fraught with complications for backwards compat :-(
    if ($backtrace[1]['function'] === 'call_user_func_fixed') {
        $called = 'call_user_func_fixed';
        $contextKey = 2;
    } else {
        $called = 'call_user_func_array_fixed';
        $contextKey = 1;
    }

    try {
        // Get a reference to the target static method if possible
        switch (true) {
            case $func[0] === 'self':
            case $func[0] === 'static':
                if (!isset($backtrace[$contextKey]['object'])) {
                    throw new Exception('Use of self:: in an invalid context');
                }

                $contextClass = new ReflectionClass($backtrace[$contextKey][$func[0] === 'self' ? 'class' : 'object']);
                $contextClassName = $contextClass->getName();

                $method = $contextClass->getMethod($func[1]);
                $ownerClassName = $method->getDeclaringClass()->getName();
                if (!$method->isStatic()) {
                    throw new Exception('Attempting to call instance method in a static context');
                }
                $invokeContext = null;

                if ($method->isPrivate()) {
                    if ($ownerClassName !== $contextClassName
                            || !method_exists($method, 'setAccessible')) {
                        throw new Exception('Attempting to call private method in an invalid context');
                    }

                    $method->setAccessible(true);
                } else if ($method->isProtected()) {
                    if (!method_exists($method, 'setAccessible')) {
                        throw new Exception('Attempting to call protected method in an invalid context');
                    }

                    while ($contextClass->getName() !== $ownerClassName) {
                        $contextClass = $contextClass->getParentClass();
                    }
                    if ($contextClass->getName() !== $ownerClassName) {
                        throw new Exception('Attempting to call protected method in an invalid context');
                    }

                    $method->setAccessible(true);
                }

                break;

            case is_object($func[0]):
                $contextClass = new ReflectionClass($func[0]);
                $contextClassName = $contextClass->getName();

                $method = $contextClass->getMethod($func[1]);
                $ownerClassName = $method->getDeclaringClass()->getName();

                if ($method->isStatic()) {
                    $invokeContext = null;

                    if ($method->isPrivate()) {
                        if ($ownerClassName !== $contextClassName || !method_exists($method, 'setAccessible')) {
                            throw new Exception('Attempting to call private method in an invalid context');
                        }

                        $method->setAccessible(true);
                    } else if ($method->isProtected()) {
                        if (!method_exists($method, 'setAccessible')) {
                            throw new Exception('Attempting to call protected method in an invalid context');
                        }

                        while ($contextClass->getName() !== $ownerClassName) {
                            $contextClass = $contextClass->getParentClass();
                        }
                        if ($contextClass->getName() !== $ownerClassName) {
                            throw new Exception('Attempting to call protected method in an invalid context');
                        }

                        $method->setAccessible(true);
                    }
                } else {
                    $invokeContext = $func[0];
                }

                break;

            default:
                $contextClass = new ReflectionClass($backtrace[$contextKey]['object']);
                $method = new ReflectionMethod($func[0], $func[1]);
                $ownerClassName = $method->getDeclaringClass()->getName();
                if (!$method->isStatic()) {
                    throw new Exception('Attempting to call instance method in a static context');
                }
                $invokeContext = null;

                if ($method->isPrivate()) {
                    if (empty($backtrace[$contextKey]['object'])
                            || $func[0] !== $contextClass->getName()
                            || !method_exists($method, 'setAccessible')) {
                        throw new Exception('Attempting to call private method in an invalid context');
                    }

                    $method->setAccessible(true);
                } else if ($method->isProtected()) {
                    $contextClass = new ReflectionClass($backtrace[$contextKey]['object']);

                    if (empty($backtrace[$contextKey]['object']) || !method_exists($method, 'setAccessible')) {
                        throw new Exception('Attempting to call protected method outside a class context');
                    }

                    while ($contextClass->getName() !== $ownerClassName) {
                        $contextClass = $contextClass->getParentClass();
                    }
                    if ($contextClass->getName() !== $ownerClassName) {
                        throw new Exception('Attempting to call protected method in an invalid context');
                    }

                    $method->setAccessible(true);
                }

                break;
        }

        // Invoke the method with the passed arguments and return the result
        return $method->invokeArgs($invokeContext, $args);
    } catch (Exception $e) {
        trigger_error($called . '() expects parameter 1 to be a valid callback: ' . $e->getMessage(), E_USER_ERROR);
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)