지향 PHP- 객체 (객체 지향 방법 및 패키지)

1.9 패키지

패키지 선택 정보를 제공 받는다

패키지는 액세스 개질제 통해 이루어진다

1.10 생성자

1.10.1 소개

또한,이 방법은 객체가 인스턴스화 될 때 구성 생성자가 자동으로 실행이라고합니다.
구문 :

function __construct(){
}
注意:前面是两个下划线

<?php
class Student {
	public function __construct() {
		echo '这是构造方法<br>';
	}
}
new Student();	//这是构造方法
new Student();	//这是构造方法

참고 : 다른 언어에서는 클래스의 함수와 같은 이름은 PHP에서 이러한 접근을 허용하지 않는 생성자입니다.

class Student {
	//和类名同名的方法是构造方法,PHP中不建议使用
	public function Student() {
		echo '这是构造方法<br>';
	}
}
/*
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Student has a deprecated constructor in F:\wamp\www\6-demo.php on line 2
这是构造方法
*/

1.10.2 생성자 함수 : 초기화 멤버 변수

<?php
class Student {
	private $name;
	private $sex;
	//构造函数初始化成员变量
	public function __construct($name,$sex) {
		$this->name=$name;
		$this->sex=$sex;
	}
	//显示信息
	public function show() {
		echo "姓名:{$this->name}<br>";
		echo "性别:{$this->sex}<br>";
	}
}
//实例化
$stu=new Student('tom','男');
$stu->show();
//运行结果
/*
姓名:tom
性别:男
*/

참고 : 생성자는 매개 변수를 할 수 있지만, 수익을 가질 수 없습니다.

출시 1891 원저 · 원 찬양 2010 ·은 180,000 + 조회수

추천

출처blog.csdn.net/weixin_42528266/article/details/105138715