PHP의 생성자

[PHP 생성자를 사용하여 클래스의 객체 속성을 초기화합니다.]

다음 예에서는 클래스를 만들고 함수를 사용하여 해당 Student속성 을 할당합니다 .__constructnew Student

__constructset_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", "[email protected]");
echo $obj->get_name();
echo "<br>";
echo $obj->get_email();
?>

산출:

John
[email protected]

[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 "<br>";
$person2 = new Military("Fred", "Commander");
$person2->show_detail();
?>

산출:

Michael : Your Rank is General
Fred : Your Rank is Commander

[ IndividualPHP에서 두 클래스 모두 생성자가 있는 경우 하위 클래스에서 객체를 시작하고 상위 클래스 생성자를 호출]

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

Identityclass는 Student위 코드의 클래스를 확장합니다. 클래스의 생성자를 parent:호출하기 위해 키워드를 사용합니다 .Student

추천

출처blog.csdn.net/weixin_50251467/article/details/131777314