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

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


当前回答

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

其他回答

__construct是一个在使用新对象之前初始化它的方法。 http://php.net/manual/en/language.oop5.decon.php#object.construct

它是用来声明构造函数的。

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

每当创建类的新实例时,构造函数都会被调用,在这种情况下,构造函数将通过以下行调用:

$cat = new Cat();

在旧的PHP版本中,构造函数也可以使用类名来声明,例如:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

构造函数允许在创建对象时初始化对象的属性。

如果你创建了__construct()函数,当你从类中创建对象时,PHP会自动调用这个函数。

https://www.w3schools.com/php/php_oop_constructor.asp

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

我希望这有助于:

<?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