__construct 函数是做什么用的?

新手上路,请多包涵

我已经注意到 __construct 很多课程。我做了一些阅读和网上冲浪,但找不到我能理解的解释。我只是从 OOP 开始。

我想知道是否有人可以让我大致了解它是什么,然后举一个简单的例子来说明它是如何与 PHP 一起使用的?

原文由 Levi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 694
2 个回答

__construct 是在 PHP5 中引入的,它是定义构造函数的正确方法(在 PHP4 中,您使用类的名称作为构造函数)。您不需要在类中定义构造函数,但如果您希望在对象构造中传递任何参数,那么您需要一个。

一个例子可能是这样的:

 class Database {
  protected $userName;
  protected $password;
  protected $dbName;

  public function __construct ( $UserName, $Password, $DbName ) {
    $this->userName = $UserName;
    $this->password = $Password;
    $this->dbName = $DbName;
  }
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

PHP 手册中解释了其他所有内容: 单击此处

原文由 Jan Hančič 发布,翻译遵循 CC BY-SA 3.0 许可协议

让我解释一下 __construct() 没有首先使用该方法… 关于 __construct() 需要了解的一点是它是一个内置函数,那么让我在 PHP 中将其称为方法。正如我们有 print_r() 用于程序, __construct() 是面向 OOP 的内置。

话虽如此,让我们探讨一下为什么应该使用这个名为 __construct() 的函数。

   /*=======Class without __construct()========*/
  class ThaddLawItSolution
   {
      public $description;
      public $url;
      public $ourServices;

      /*===Let us initialize a value to our property via the method set_name()==== */
     public function setName($anything,$anythingYouChoose,$anythingAgainYouChoose)
     {
      $this->description=$anything;
      $this->url=$anythingYouChoose;
      $this->ourServices=$anythingAgainYouChoose;
    }
    /*===Let us now display it on our browser peacefully without stress===*/
    public function displayOnBrowser()
    {
       echo "$this->description is a technological company in Nigeria and our domain name is actually $this->url.Please contact us today for our services:$this->ourServices";
    }

 }

         //Creating an object of the class ThaddLawItSolution
$project=new ThaddLawItSolution;
        //=======Assigning Values to those properties via the method created====//
$project->setName("Thaddlaw IT Solution", "https://www.thaddlaw.com", "Please view our website");
      //===========Let us now display it on the browser=======
$project->displayOnBrowser();

__construct() 让您的生活变得非常轻松,想象一下我通过该方法为这些属性分配值所花费的时间。从上面的代码中,我首先创建了一个对象,然后将值分配给第二个属性,最后在浏览器上显示它。但是在创建对象时使用 __construct()$project= new ThaddLawItSolution; 您可以在创建对象时立即为该方法分配值,即

$project=new ThaddLawItSolution("Thaddlaw IT Solution", "https://www.thaddlaw.com","Please view our website");

//===让我们现在使用 __constructor=====

只需删除名为 setName 的方法并放入 __construct(); 并在创建对象时立即分配值。这就是整个 __construct() 方法背后的要点。但请注意,这是一个内置的方法或函数

原文由 Godswill 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题