我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。

我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?


当前回答

我认为这对于理解构造函数的目的很重要。 即使在阅读了这里的回复后,我也花了几分钟才意识到这是原因。 我已经养成了一个习惯,即显式地编码所有启动或发生的事情。换句话说,这将是我的猫类,我将如何称呼它。

class_cat.php

class cat {
    function speak() {
        return "meow";  
    }
}

somepage.php

include('class_cat.php');
mycat = new cat;
$speak = cat->speak();
echo $speak;

在@Logan Serman给出的“类猫”的例子中,假设每次你创建一个类“猫”的新对象时,你都希望猫“喵”,而不是等待你调用函数让它喵。

通过这种方式,我的大脑在明确地思考构造函数方法使用隐式的地方,这使得它一开始很难理解。

其他回答

我认为函数__construct(){…}是一段可以重复使用的代码,可以替代TheActualFunctionName(){…}。 如果你改变了类名,你不需要在代码中改变,因为泛型__construct总是引用实际的类名…不管是什么。 你写的代码少了…还是?

构造函数是一个在类实例化时自动调用的方法。这意味着构造函数的内容不需要单独的方法调用就可以处理。类关键字括号的内容被传递给构造函数方法。

__construct只是简单地启动一个类。假设您有以下代码;

Class Person { 

 function __construct() {
   echo 'Hello';
  }

}

$person = new Person();

//the result 'Hello' will be shown.

我们没有创建另一个函数来响应单词“Hello”。它只是表明关键字__construct在初始化类或对象时非常有用。

我希望这有助于:

<?php
    // The code below creates the class
    class Person {
        // Creating some properties (variables tied to an object)
        public $isAlive = true;
        public $firstname;
        public $lastname;
        public $age;

        // Assigning the values
        public function __construct($firstname, $lastname, $age) {
          $this->firstname = $firstname;
          $this->lastname = $lastname;
          $this->age = $age;
        }

        // Creating a method (function tied to an object)
        public function greet() {
          return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)";
        }
      }

    // Creating a new person called "boring 12345", who is 12345 years old ;-)
    $me = new Person('boring', '12345', 12345);

    // Printing out, what the greet method returns
    echo $me->greet(); 
    ?>

更多信息请访问codecademy.com

注意:如果子类定义了构造函数,父构造函数不会隐式调用。为了运行父构造函数,需要在子构造函数中调用parent::__construct()。如果子类没有定义构造函数,那么它可以像普通的类方法一样从父类继承(如果它没有声明为private)。