实例
/**
*1.对象的创建
* 2.对象成员的初始化
* 3.对象成员的访问
*/
// 导入类
require 'class/GirlFriend1.php';
// 实例化类,创建对象的过程
$girlfriend1 = new GirlFriend1();
//var_dump($girlfriend1);
echo $girlfriend1->name,'
'; // 访问类中成员中的属性变量
echo $girlfriend1->getInfo(), '
'; // 访问类中成员中的方法函数
echo $girlfriend1->getInfo('金莲',30), '
'; // 访问类中成员中的方法函数
echo $girlfriend1->getStature([120,130,180]),'
';
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
class GirlFriend1
{
// 类中的成员: 属性(变量),方法(函数)
// 类中用类似变量的方式定义类的属性
//姓名,public 是访问控制,
public $name = '冰冰姐';
//年龄
public $age = 18;
// 三维
public $stature = [90,80,90];
//类中使用类似函数的方式来定义方法
public function getInfo($name='', $age=0)
{
// $this: 当前类被实例化之后的对象, -> 对象成员访问符
$this->name = empty($name) ? $this->name : $name;
$this->age = ($age == 0) ? $this->age : $age;
return '姓名:' . $this->name . ', 年龄:' . $this->age. '
';
}
public function getStature($stature =[])
{
// $this: 当前类被实例化之后的对象, -> 对象成员访问符
$this->stature = empty($stature) ? $this->stature : $stature;
return '胸围:' . $this->stature[0] . ', 腰围:' . $this->stature[1]. ',臀围:'. $this->stature[2].'
';
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
/**
* 1.使用构造方式来初始化对象
* 2. 对象的访问控制,public,private
* 3. 对象属性的获取器/ getter 和 修改器 / setter
*/
require 'class/GirlFriend2.php';
$girlfriend2 = new GirlFriend2('金莲妹妹',23,[87,88,89]);
//echo $girlfriend2->name,'
';
echo $girlfriend2->getName('西门大官人');
$girlfriend2->setAge(139);
//echo $girlfriend2->getAge();
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
class GirlFriend2
{
//访问控制: private
private $name;
//年龄
private $age;
// 三维
private $stature = [];
// 声明构造方法: 对象属性的初始化,在类实例化的时候,自动调用
public function __construct($name, $age, array $stature)
{
// private 访问符限制的属性仅在当前对象内部可以使用
$this->name = $name;
$this->age = $age;
$this->stature = $stature;
}
//创建对外访问的公共接口
public function getName($yourName='')
{
$msg = '非法访问';
if (!empty($yourName) && $yourName == '武大郎') {
$msg = $this->name;
}
return $msg;
}
//设置器
public function setAge($age=0)
{
if ($age >=0 && $age <=120) {
$this->age = $age;
}
echo '非法数据';
}
//获取器
public function getAge()
{
return $this->age;
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
require 'class/GirlFriend3.php';
$girlfriend3 = new GirlFriend3('冰冰姐',38,[98,128,188]);
echo $girlfriend3->name,'
';
echo $girlfriend3->age,'
';
$girlfriend3->age = 45;
echo $girlfriend3->age,'
';
echo $girlfriend3->email,'
';
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
class GirlFriend3
{
//访问控制: private
private $name;
//年龄
private $age;
// 三维
private $stature = [];
//属性收集器
private $data = [];
// 声明构造方法: 对象属性的初始化,在类实例化的时候,自动调用
public function __construct($name, $age, array $stature)
{
// private 访问符限制的属性仅在当前对象内部可以使用
$this->name = $name;
$this->age = $age;
$this->stature = $stature;
}
//创建对外访问的公共接口
// 类中用双下划线的方法是系统定义,由系统自动调用,叫魔术方法
public function __get($name)
{
$msg = null;
if (isset($this->$name)) {
$msg = $this->$name;
} elseif (isset($this->data[$name])) {
$msg = $this->data[$name];
} else {
$msg = '无此属性';
}
return $msg;
}
//设置器
public function __set($name, $value)
{
$this->$name = $value;
}
}
运行实例 »
点击 "运行实例" 按钮查看在线实例