1

我已经看过有关此的主题,并且我了解它的工作原理。但这不是很混乱吗?使用self::someMethod()我们打算停止多态行为,并且我们希望不再依赖于子类中可能的覆盖。但是这个例子(非常不自然,但仍然)表明这种期望会导致意想不到的错误。假设,我们有类层次结构 Shape->Rectangle->Square,并且还有其他东西有用于计算面积的静态方法:

abstract class Shape {
    //"abstract" `area` function which should be overriden by children
    public static function area(array $args) {
       throw new Exception("Child must override it");
    }

    //We also provide checking for arguments number.
    static function areaNumArgs(){
      throw new Exception("Child must override it");
    }

    final static function checkArgsNumber (array $args) {
        return count($args) == static::areaNumArgs(); 
        //With 'static' we use late static binding
    }
}

class Rectangle extends Shape {
    static function areaNumArgs(){return 2;} //Arguments are lengths of sides

    static function area(array $args) {
        //Algorithm is stupid, but I want to illustrate result of 'self'
        $n = self::areaNumArgs(); 
        /*With 'self' we DON'T use polymorphism so child can 
        override areaNumArgs() and still use this method.
        That's the point of 'self' instead of 'static', right?*/
        $area = 1;
        for($i = 0; $i<$n; $i++) $area *= $args[$i];
        return $area;
    }

    //Let's wrap call to 'area' with checking for arguments number
    static function areaWithArgsNumberCheck (array $args)
    {
        if(self::checkArgsNumber($args)) 
            return self::area($args);
            //We use 'self' everywhere, so again no problem with 
            //possible children overrides?
        else
            return false;
    }
}

var_dump(Rectangle::areaWithArgsNumberCheck(array(3,2))); 
//output is 6, everything OK.

//Now we have Square class.
class Square extends Rectangle {
    static function areaNumArgs(){return 1;} 
    //For square we only need one side length

    static function area(array $args) {
        //We want to reuse Rectangle::area. As we used 'self::areaNumArgs', 
        //there is no problem that this method is overriden.
        return parent::area(array($args[0], $args[0]));
    }

    static function areaAnotherVersion(array $args) {
        //But what if we want to reuse Rectangle::areaWithArgsNumberCheck? 
        //After all, there we also used only 'self', right?
        return parent::areaWithArgsNumberCheck(array($args[0], $args[0]));
    }
}

var_dump(Square::area(array(3))); //Result is 9, again everything OK.

var_dump(Square::areaAnotherVersion(array(3))); //Oops, result is FALSE

这是因为虽然Rectangle::areaWithArgsNumberCheck只使用了 'self',但它调用了Shape::checkArgsNumber使用static::areaNumArgs. 最后一次调用被解析为Square类,因为self::调用转发了静态绑定。

这个问题很容易通过使用类名 ( Rectangle::) 而不是self::

所以对我来说,如果有一些 static调用,那么该类层次结构中的所有调用都应该static明确地使用类名。您只是永远不知道self::呼叫将被转发到哪里以及将使用哪些可能被覆盖的方法。我对此是否正确,或者在某些情况下,使用“self”转发静态绑定可能有用且安全?

4

0 回答 0