【问题标题】:Constructor in PHPPHP中的构造函数
【发布时间】:2017-08-13 05:50:40
【问题描述】:

PHP 中的构造方法是否接受类中声明的参数?

我在多个网站和书籍以及 PHP 文档中看到函数函数 __construct() 不带任何参数。

【问题讨论】:

  • __construct 可以采用与任何其他方法相同的参数。
  • 你一定是读错了书籍和文档——构造函数可以使用你定义的任意数量的参数
  • 如有疑问 - 只需阅读官方文档中的此类内容,而不是依赖第三方资源。 php.net/manual/en/language.oop5.decon.php
  • 其实我想知道你所说的“类中声明的参数”是什么意思......一个类没有声明的参数,只有方法(函数)有。构造函数就是这样一种方法。它将接受在其实现中声明的任何参数。

标签: php class methods constructor


【解决方案1】:

__construct 可以带参数。根据the official documentation,这个方法签名是:

void __construct ([ mixed $args = "" [, $... ]] )

看来它可以带参数!

使用方法:

class MyClass {
    public function __construct($a) {
        echo $a;
    }
}

$a = new MyClass('Hello, World!'); // Will print "Hello, World!"

【讨论】:

    【解决方案2】:

    PHP 构造函数可以像其他函数一样接受参数。 __construct()函数不需要加参数,例如:

    示例 1:无参数

    <?php
    class example {
        public $var;
        function __construct() {
            $this->var = "My example.";
        }
    }
    
    $example = new example;
    echo $example->var; // Prints: My example.
    ?>
    

    示例 2:带参数

    <?php
    class example {
        public $var;
        function __construct($param) {
            $this->var = $param;
        }
    }
    
    $example = new example("Custom parameter");
    echo $example->var; // Prints: Custom parameter
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-15
      • 2012-06-30
      • 2014-04-02
      • 1970-01-01
      • 2011-12-05
      • 2011-03-06
      • 2011-03-03
      • 1970-01-01
      相关资源
      最近更新 更多