PHP 类的初始化方法
作者:慢热型
时间:2024-02-27
浏览:0
在本文中,我们将介绍PHP构造函数。我们将看到如何使用__construct()函数来初始化类中实例的属性。我们还将使用该函数来初始化类中具有给定参数的对象的属性。最后,我们将看到如何在子类中启动对象并在两个类都有单独的构造函数时调用父类构造函数。使用php构造函数初始化类中的对象的属性在下面的示例中,我们将创建一个类Student并使用__construct函数为newStudent分配其属性。__construct函数减少了与使用函数set_name()相关的代码数量。<?phpclassStu
在本文中,我们将介绍 PHP 构造函数。我们将看到如何使用 __construct() 函数来初始化类中实例的属性。
我们还将使用该函数来初始化类中具有给定参数的对象的属性。
最后,我们将看到如何在子类中启动对象并在两个类都有单独的构造函数时调用父类构造函数。
使用 php 构造函数初始化类中的对象的属性
在下面的示例中,我们将创建一个类 Student 并使用 __construct 函数为 new Student 分配其属性。
__construct 函数减少了与使用函数 set_name() 相关的代码数量。
php
class Student {
// Define the attributes of your class
public $name;
public $email;
// Initialize the properties of the object you want to create in this class
function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
function get_name() {
return $this->name;
}
function get_email() {
return $this->email;
}
}
$obj = new Student("John", "john567@gmail.com");
echo $obj->get_name();
echo "
";
echo $obj->get_email();
?>
输出:
John
john567@gmail.com
使用 PHP 构造函数在类中初始化 Object with Parameters 的属性
在下面的示例代码中,我们创建类 Military 并使用 __construct 函数来提供我们创建的对象的属性和参数。
php
class Military {
// Define the attributes of the class 'Military'
public $name;
public $rank;
function __construct($name, $rank){
$this->name = $name;
$this->rank = $rank;
}
function show_detail() {
echo $this->name." : ";
echo "Your Rank is ".$this->rank."\n";
}
}
$person_obj = new Military("Michael", "General");
$person_obj->show_detail();
echo "
";
$person2 = new Military("Fred", "Commander");
$person2->show_detail();
?>
输出:
Michael : Your Rank is General
Fred : Your Rank is Commander
在 PHP 中在子类中启动一个对象并在两个类都有 Individual 构造函数时调用父类构造函数
php
class Student
{
public $name;
public function __construct($name)
{
$this->name = $name;
}
}class Identity extends Student
{
public $identity_id;
public function __construct($name, $identity_id)
{
parent::__construct($name);
$this->identity_id = $identity_id;
}
function show_detail() {
echo $this->name." : ";
echo "Your Id Number is ".$this->identity_id."\n";
}
}
$obj = new Identity('Alice', '1036398');
echo $obj->show_detail();
?>
输出:
Alice : Your Id Number is 1036398
Identity 类扩展了上述代码中的 Student 类。我们使用关键字 parent: 来调用 Student 类的构造函数。
作者最新文章
网易2026年Q2财报:营收301亿元,游戏收入增10%,三款重点新游披露进展
2026-09-08 17:51
PDF怎么添加页码?页码位置和起始页怎么设置?
2026-09-03 09:11
图片文件怎么转换成PDF?多张图片如何按顺序合成?
2026-09-02 19:33
CorelDRAW绘制正弦曲线的两种方法:贝塞尔工具与变形工具
2026-09-02 16:08
Excel工作表制作教程:设计易填写、易统计的业务表
2026-09-02 12:11
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































