php后期静态绑定和' self'电话

时间:2017-01-15 02:37:01

标签: php late-static-binding

我已经看过topic这件事,我明白它是如何运作的。 但这不是很混乱吗?使用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仅使用&#39; self&#39;,但它调用了使用Shape::checkArgsNumber的{​​{1}}。最后一次调用已解决为static::areaNumArgs类,因为Square调用转发的静态绑定。

使用班级名称(self::)代替Rectangle::

可轻松解决问题

所以对我来说,如果有一些 self::调用,那么该类层次结构中的所有调用都应该明确地使用static个使用类名。您永远不知道将转发static调用的位置以及将使用哪些可能的覆盖方法。我对此是正确的,还是存在使用&#39; self&#39;转发静态绑定的情况。可能有用且安全吗?

0 个答案:

没有答案