【问题标题】:What is the difference between the two types of class constructors in PHP?PHP中这两种类构造函数有什么区别?
【发布时间】:2012-05-14 18:29:45
【问题描述】:

使用__construct构造函数和使用类名作为构造函数时,PHP类到底有什么区别?

例如:

class Some
{
     public function __construct($id)
     {
           ....
     }
     ....
}

class Some
{
      public function Some($id)
      {
            ....
      }
      ....
}

【问题讨论】:

    标签: php class constructor


    【解决方案1】:

    顶部是 PHP 5.0 版本的新方式,也是所有新代码的编写方式。后者是旧的 PHP 4 方式并且已过时。在某些时候,它将完全弃用并从 PHP 中完全删除。

    更新

    As of PHP 5.3.3,与命名空间类名的最后一个元素同名的方法将不再被视为构造函数。此更改不会影响非命名空间类。

    <?php
    namespace Foo;
    class Bar {
        public function Bar() {
            // treated as constructor in PHP 5.3.0-5.3.2
            // treated as regular method as of PHP 5.3.3
        }
    }
    ?>
    

    【讨论】:

    • 根据PHP manual 已在 5.3.3 中弃用。参见示例 #2
    • 感谢您的信息。我会相应地更新我的答案。
    猜你喜欢
    • 2015-12-26
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    相关资源
    最近更新 更多