PHP의 생성자

王林
풀어 주다: 2024-08-29 12:42:06
원래의
853명이 탐색했습니다.

생성자는 PHP5 OOP(객체 지향 프로그래밍) 개념입니다. 생성자는 프로그램에서 선언한 클래스와 연결됩니다. 생성자는 클래스의 객체가 인스턴스화될 때 자동으로 호출되므로 생성자의 정의는 "생성자는 클래스의 객체가 인스턴스화될 때 자동으로 호출되는 특수 메서드"입니다. 이번 주제에서는 PHP의 생성자에 대해 알아보겠습니다.

광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

<?php
Class Classname {
//constructor
function __construct() {
//statements
}
}
?>
로그인 후 복사

위 코드에서 생성자는 __ 이중 밑줄로 시작하고 그 뒤에 키워드 구문이 옵니다. __construct()가 없는 생성자 또는 클래스 이름이 변경된 경우 정의된 메서드는 생성자가 아닌 메서드일 뿐입니다. 따라서 정의된 구문에 따라 클래스의 생성자를 정의하는 것이 중요합니다.

생성자의 종류

다음은 생성자의 일부 유형과 해당 출력이 아래에 나와 있습니다

1) 사전 정의된 생성자

미리 정의된 생성자에 대해 명확히 설명하기 위해 아래 예시를 살펴보겠습니다

미리 정의된 생성자의 예

코드:

<?php
class Person {
function  CanSpeak() {
echo " Not a constructor method " . '<br>';
}
function __construct() {
echo " In the constructor method " . '<br>';
}
}
//Object of class calling the constructor internally
$p = new Person();
// Object of class calling the normal method
$p->CanSpeak();
?>
로그인 후 복사

출력:

PHP의 생성자

위의 예에서

Person 클래스에는 Person CanSpeak() 메서드와 생성자 메서드 __construct()라는 두 가지 메서드가 있습니다. 다음으로 클래스를 $p 객체로 인스턴스화했습니다. $p를 사용하여 일반 메소드를 호출했습니다. 객체가 생성되자마자 생성자 메소드가 호출되고 메소드 내부의 명령문이 실행되며, 마찬가지로 동일한 객체 $p와 내부 명령문을 사용하여 생성자 메소드가 아닌 일반 메소드인 CanSpeak() 메소드가 호출됩니다. 해당 메소드가 실행됩니다. 또한 위에서 정의한 생성자에는 인수가 없으므로 이를 인수가 없는 생성자 또는 미리 정의된 생성자라고 부릅니다.

2) 매개변수화된 생성자

생성자에는 인수가 있을 수도 있고 없을 수도 있습니다. 인수가 있는 생성자를 매개변수화된 생성자라고 하고, 인수가 없는 생성자를 인수가 없는 생성자라고 합니다. 예시를 살펴보겠습니다.

매개변수화된 생성자의 예

코드:

class Person {
private $first;
private $email;
private $mobile;
public function __construct($name, $email, $mobile) {
echo "Initialising the object...<br/>";
$this->name = $name;
$this->email = $email;
$this->mobile = $mobile;
}
public function showProfile() {
echo "My name is: " . $this->name. " " . $this->email. " " . $this->mobile;
}
}
$john = new Person("John","[email protected]", "9187986786");
$john->showProfile();
로그인 후 복사

출력:

PHP의 생성자

생성자는 어떻게 작동하나요?

실행할 자체 생성자와 실행할 상위 생성자가 있는 extends 키워드를 사용하여 기본 클래스를 확장하는 기본 클래스 생성자와 파생 클래스를 살펴보겠습니다. 지금까지 우리는 클래스에 선언된 생성자에 대해서만 배웠습니다. 여기서 생성자에 대한 지식을 더 추가해 보겠습니다. 다음 예에서 기본 클래스 Person에는 생성자가 있습니다. 이제 이 생성자는 파생 클래스 또는 부모 키워드를 사용하여 하위 클래스에 의해 호출되므로 기본 클래스 Person의 생성자에 액세스할 수 있습니다.

출력 흐름

먼저 Person 생성자가 호출된 다음 내부적으로 Person 생성자를 다시 호출하는 Customer 생성자가 호출되고 그 다음 자체 고객 생성자와 마지막으로 Person 클래스를 확장하는 Employee 클래스가 호출되므로 Person 생성자가 다시 호출됩니다.

코드:

class Person {
function __construct() {
echo "In Person constructor"."<br>";
}
}
class Customer extends Person  {
function __construct() {
parent::__construct();
echo "In Customer constructor"."<br>";
}
}
class Employee extends Person  {
// inherits Person’s constructor
}
// In Person constructor
$p = new Person();
// In Person constructor
// In Customer constructor
$c = new Customer();
// In Employee constructor
$e = new Employee();
로그인 후 복사

출력:

PHP의 생성자

아래 예에서는 set 메소드와 get 메소드가 어떻게 작동하는지 보여줍니다. OOP에서 캡슐화 개념을 사용합니다. 처음에 프로그램은 생성자, set_name 메소드 및 get_name 메소드를 사용하여 선언됩니다. 생성자는 클래스가 인스턴스화될 때 확실히 호출되는 매개변수화된 생성자이므로 첫 번째 출력은 John Doe가 다음에 클래스의 객체를 생성하고 출력을 Alice로 인쇄하는 set_name 및 get_name 메서드를 호출하는 것입니다.

코드:

<?php
class Person {
public $name;
function __construct($name) {
echo $this->name = $name;
}
function set_name($name) {
$this->name = $name;
}
function get_name() {
echo $this->name;
}
}
// In Person constructor
$p = new Person('John Doe');
echo "\n";
$p->set_name('Alice');
$p->get_name();
?>
로그인 후 복사

출력:

PHP의 생성자

액세스 지정자

PHP에는 세 가지 액세스 지정자가 있습니다

  • 공개
  • 보호됨
  • 비공개

공개: 공개로 선언된 클래스의 구성원은 어디에서나 액세스할 수 있습니다.

Protected: Members of the class declared as protected are accessible only within the base class and the derived class which extends the base class.

Private: Members of the class declared as private are accessible with the class that defines it.

Also, the variables declared are called data members or properties and the functions declared are called as data methods. In the below example we have Base Class declared as Person which has the following properties along with the access specifiers public name, protected email and private mobile. Now the class is instantiated with an object $p and these three properties which are accessed from the object. which outputs are an error, why because, the protected property says that protected are accessible only within the base class and the derived class which extends the base class?

Code:

<?php
class Person {
public $name=;
protected $email;
private $mobile;
function __construct() {
print "In Person constructor";
}
}
// In Person constructor
$p = new Person();
echo $p->name;
echo $p->email;
echo $p->mobile;
?>
로그인 후 복사

Output:

PHP의 생성자

Conclusion

Hope this article finds you what you have been searching for. The article has different examples for you to learn. The more you put the examples in practice the easier it will become to grasp.

위 내용은 PHP의 생성자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
php
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!