当程序员需要对静态属性进行操作时,就需要定义静态方法处理,静态方法是专门操作静态属性的
class 类名{
访问修饰符 static function 函数名 (){
//函数体
}
}
说明:
小案例:
<?php
//静态方法
class Person{
public $name;
private static $age=18;
//静态方法来操作静态属性
public static function getAge(){
echo '年龄是 '.self::$age;
}
}
//通过类名在外部直接调用静态方法
Person::getAge();
?>
案例:
<?php
//静态方法
class Person{
public $name;
private static $age=18;
//构造方法
public function __construct($name){
$this->name=$name;
}
//静态方法来操作静态属性
public static function getAge(){
echo '年龄是 '.self::$age;
//静态方法中只能访问静态属性,不能访问非静态属性
//echo $this->name.'的年龄是 '. self::$age;//这样写是错误的 不能访问非静态属性
//echo self::$name.'的年龄是 '. self::$age;//这样写也是错误的 不能访问非静态属性
}
//在类的内部调用静态方法
public function show(){
//方法一:self::方法名
self::getAge();
//方法二:类名::方法名
Person::getAge();
//方法三:$this->方法名
$this->getAge();
}
}
//通过类名在外部直接调用静态方法
Person::getAge();
//在类的外部通过对象调用静态方法
$person = new Person('张三');
$person->getAge();
//在类的外部通过对象名::静态方法调用
$person::getAge();
$person->show();
?>
编写一个操作数据库的工具类,要求只能创建一个对象
<?php
//编写一个操作数据库的工具类,要求只能创建一个对象
class DaoMysql{
//定义需要的属性
//连接数据库
private $mysql_link;
//定义一个静态属性,用来类的对象实例
private static $instance = null;
//构造方法
public function __construct($host,$user,$pass){
//这里只连接一次数据库,减少资源
$this->mysql_link = @mysql_connect($host,$user,$pass);
echo $this->mysql_link;
}
//写一个静态方法,通过这个静态方法来创建对象实例
public static function getSingleton($host,$user,$pass){
//通过getSingleton来创建对象
//判断控制是否已经创建过对象
if(self::$instance == null){
self::$instance = new DaoMysql($host,$user,$pass);
}
return self::$instance;
}
//阻止克隆
private function __clone(){}
}
$dao1 = DaoMysql::getSingleton('localhost','root','');
$dao2 = DaoMysql::getSingleton('localhost','root','root');
var_dump($dao1,$dao2);//结果都是同一个对象
?>
另一种写法(推荐)
instance是类型运算符,它用于判断某个变量是否是某个类的对象
<?php
//编写一个操作数据库的工具类,要求只能创建一个对象
class DaoMysql{
//定义需要的属性
//连接数据库
private $mysql_link;
//定义一个静态属性,用来类的对象实例
private static $instance = null;
//构造方法
public function __construct($host,$user,$pass){
//这里只连接一次数据库,减少资源
$this->mysql_link = @mysql_connect($host,$user,$pass);
echo $this->mysql_link;
}
//写一个静态方法,通过这个静态方法来创建对象实例
public static function getSingleton($host,$user,$pass){
//通过getSingleton来创建对象
//判断控制是否已经创建过对象
/* //第一种写法
if(self::$instance == null){
self::$instance = new DaoMysql($host,$user,$pass);
}
return self::$instance;
} */
//第二种写法
//instanceof是类型运算符,它用于判断某个变量是否是某个类的对象
if(!self::$instance instanceof self){
self::$instance = new self($host,$user,$pass);
}
return self::$instance;
}
//阻止克隆
private function __clone(){}
}
$dao1 = DaoMysql::getSingleton('localhost','root','');
$dao2 = DaoMysql::getSingleton('localhost','root','root');
var_dump($dao1,$dao2);//结果都是同一个对象
?>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有