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
性别:男
*/

注意:构造函数可以带参数,但不能有return。

发布了1891 篇原创文章 · 获赞 2010 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/105138715
今日推荐