开发者

PHP4 constructor naming convention in PHP5

Aside from the "you won't have to开发者_JAVA技巧 change the name", is there any real problems with retaining the PHP4 style constructor names:

ClassName($args)

in PHP5?


Because named constructors were only retained in PHP5 for backwards compatibility with PHP4, they are more likely to become deprecated in a later release of PHP than __construct() is, so that's something to keep in mind if you're writing something that you intend to have longevity.


If you use the old style constructor names, you're creating a bit of confusion around situations like this

class A
{
    public function A()
    {
    }
}

class B extends A
{
    public function B()
    {
        //how do/should I call the parent constructor?
        //parent::A(); ?
        //parent::__construct(); ?
    }
}

If someone sees the old style constructor and switches it to a less-old style constructor, you risk functionality breaking. Also, if you have to juggle your object heirarchy so that B extends a different class, you need to manually change all the calls to parent::A(), or someone not familiar with the "constructor is a method with the class name" construct (meaning anyone who learned PHP in the last 5 years) may not know to do that and subtle breaking will occur.


For PHP5, there's no problem with retaining it. However, if the class has a __construct() function, it will be called instead.


According to the documentation, that's the only drawback.


No. Besides that it's ugly-ish (imo) and takes away one possible function name. ^^


in php 4 oop is more a hack than everything else here is a code snipped for a constructor in php 5 style but its compatible for php 4

class Object
{
    function Object()
    {
        $args= func_get_args();
        call_user_func_array
        (
            array(&$this, '__construct'),
            $args
        );
    }

    function __construct()
    {
        // Abstrakt Funktion
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜