Неправильный статический метод

PHP вызывает частный метод в родительском классе вместо метода define в текущем классе, называемом 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

Ответы

Ответ 1

Это ошибка, которая долгое время колебалась и выходила из жизни (см. тесты @deceze в комментариях к вопросу). Можно "исправить" эту проблему, то есть дать последовательное поведение в версиях PHP, используя reflection:

Работает в PHP 5.3.2 и более поздних версиях из-за зависимости от ReflectionMethod::setAccessible() для вызова частных/защищенных методов. Я добавлю дополнительные объяснения для этого кода, что он может и не может сделать и как это работает очень скоро.

К сожалению, это невозможно проверить непосредственно на 3v4l.org, потому что код слишком велик, однако это первый реальный случай использования minifying PHP-код - он работает на 3v4l, если вы это сделаете, поэтому не стесняйтесь играть и видеть, можете ли вы его сломать. Единственная проблема, о которой я знаю, это то, что она в настоящее время не понимает parent. Он также ограничен отсутствием поддержки $this в закрытии до 5.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;
    }
}

Ответ 2

Я нашел решение с другим подходом.

<?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();
  ?>

Использование Late Static Binding..

Ответ 3

Вы можете использовать что-то вроде этого:

<?php

class Car {
    public function run() {
        return static::getName();
    }

    private static function getName(){
        return 'Car';
    }
}

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

$car = new Car();
echo $car->run();

echo PHP_EOL;

$toyota = new Toyota();
echo $toyota->run();

?>

Вывод:

Car
Toyota

PHP 5.4.5

Ответ 4

Используйте "защищенный" модификатор, если вы хотите получить доступ только от родителя и потомков. ИМО, это очевидно. Например:

<?php

class Car {
    public function run() {
        return call_user_func(array('static','getName'));
    }
    protected static function getName() {
        return 'Car';
    }
}

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

$car = new Car();
echo $car->run(); // "Car"

$toyota = new Toyota();
echo $toyota->run(); // "Toyota"

Вы можете использовать get_called_class() вместо "static".

Ответ 5

Проблема, я думаю, связана с разными уровнями доступа двух функций getname. Если вы делаете общедоступную версию getname() общедоступной (так же, как версия производного класса), то в php 5.3.15 (на моем Mac) вы получаете Toyota. Я думаю, что из-за разных уровней доступа вы получаете две разные версии функции getname() в классе Toyota, а не версию производного класса, переопределяющую версию базового класса. Другими словами, вы перегружаете, а не переопределяете. Поэтому, когда функция run() ищет функцию getname() в классе Toyota для выполнения, она находит два и берет первый, который будет первым, который будет объявлен (из базового класса).

Конечно, это просто предположение с моей стороны, но это звучит правдоподобно.

Ответ 6

используйте функцию get_called_called для этого

public function run() {
    $self = get_called_class();
    return $self::getName();
}

Ответ 7

Я считаю, что вы выполняете функции, переопределяя друг друга и по умолчанию переходите к первому. Если вы не измените параметры одной функции или не переименуете функцию, она всегда будет по умолчанию использовать функцию родительского класса.