类是对象的模板, 对象是类的实例
实例代码
<?php
class Stu{//类名
const NATIONAL = 'CHINA';//类常量 关键字const
public $name = '名字';//public: 公开,在类的内部,外部都可以访问
private $age = 44;//private: 私有,仅在本类内部访问,外部以及子类均不能访问
protected $salary = 2000;//protected: 受保护,仅在类的内部,以及子类中的访问
//为私有或受保护变量提供公共访问接口
public function getAge(){
return $this->age;
}
public function getSalary(){
return $this->salary;
}
}
$stu = new Stu();//关键字 new 实例化一个类
echo "国籍:".$stu::NATIONAL."<br>";//::访问静态成员
echo "姓名:".$stu->name."<br>";// ->访问动态成员 . 点符合连接变量和字符串
echo "年龄:",$stu->getAge(),"<br>";// , 逗号连接方法与字符串
echo "工资:",$stu->getSalary(),"<hr>";
class Stu1{
public $name ;
public $age ;
public $salary ;
//构造器,在对象实例化时(被创建时)自动调用,可用该方法对属性初始化
public function __construct($name,$age,$salary)
{
$this->name = $name;
$this->age = $age;
$this->salary = $salary;
}
}
$student = new Stu1('Eddie',32,1000);
print_r($student);
echo "<br>";
echo "<pre>",var_export($student),"</pre>";运行结果:
国籍:CHINA
姓名:名字
年龄:44
工资:2000
Stu1 Object ( [name] => Eddie [age] => 32 [salary] => 1000 )
Stu1::__set_state(array(
'name' => 'Eddie',
'age' => 32,
'salary' => 1000,
))
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号