我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。
我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?
我已经注意到__construct有很多类。我读了一些书,上网浏览了一下,但我找不到我能理解的解释。我只是从面向对象编程开始。
我想知道是否有人能给我一个大概的概念,然后是一个简单的例子,它是如何与PHP一起使用的?
当前回答
__construct总是在创建新对象时调用,或者在初始化时调用。它适用于对象在使用之前可能需要的任何初始化。__construct方法是类中执行的第一个方法。
class Test
{
function __construct($value1,$value2)
{
echo "Inside Construct";
echo $this->value1;
echo $this->value2;
}
}
//
$testObject = new Test('abc','123');
其他回答
构造函数是一个在类实例化时自动调用的方法。这意味着构造函数的内容不需要单独的方法调用就可以处理。类关键字括号的内容被传递给构造函数方法。
__construct()是构造函数的方法名。构造函数在对象创建后被调用,是放置初始化代码等的好地方。
class Person {
public function __construct() {
// Code called for each new Person we create
}
}
$person = new Person();
构造函数可以以正常的方式接受参数,这些参数是在创建对象时传递的。
class Person {
public $name = '';
public function __construct( $name ) {
$this->name = $name;
}
}
$person = new Person( "Joe" );
echo $person->name;
与其他一些语言(如Java)不同,PHP不支持重载构造函数(即拥有多个接受不同参数的构造函数)。您可以使用静态方法来实现此效果。
注意:我从(在撰写本文时)接受的答案的日志中检索到这个。
__construct总是在创建新对象时调用,或者在初始化时调用。它适用于对象在使用之前可能需要的任何初始化。__construct方法是类中执行的第一个方法。
class Test
{
function __construct($value1,$value2)
{
echo "Inside Construct";
echo $this->value1;
echo $this->value2;
}
}
//
$testObject = new Test('abc','123');
__construct方法用于在第一次创建对象时传入参数——这被称为“定义构造函数方法”,是一种常见的做法。
然而,构造函数是可选的——所以如果你不想在对象构造时传递任何参数,你就不需要它。
So:
// Create a new class, and include a __construct method
class Task {
public $title;
public $description;
public function __construct($title, $description){
$this->title = $title;
$this->description = $description;
}
}
// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');
// Try it and see
var_dump($task->title, $task->description);
有关什么是构造函数的更多细节,请参阅手册。
我希望这有助于:
<?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