PHP面向对象

本文详细对比了PHP类中构造函数和析构函数的使用方式,与C++、Java的相似之处及区别。同时,介绍了PHP对象的内存管理机制,包括引用计数原理和析构函数的自动调用。通过示例代码,深入浅出地解释了这些概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PHP对象是与java,c++几点异同,

1.PHP 类可以复写构造函数__construct和析构函数,这一点与c++相似,如果不写则默认为无参构造和析构函数

<?php
class NBAPlayer {
}
$jordan = new NBAPlayer();
复写构造和析构函数

<?php
class NBAPlayer {
	public $name;
	public $height;
	public $weight;
	public $team;
	public $teamNumber;

	function __construct($name,$height,$weight,$team,$teamNumber){
		$this->name = $name;
		$this->height = $height;
		$this->weight = $weight;
		$this->team = $team;
		$this->teamNumber = $teamNumber;
		echo "construc a instance:".$name."<br/>";
	}
	function __destruct(){
		echo "Destroy a instance:".$this->name."<br/>";
	}
}
$jordan = new NBAPlayer("jordan","198cm","98kg","bull","23");
$james = new NBAPlayer("james","205cm","120kg","heat","10");

2. $jordan 是一个对象的引用,并且php对象的内存释放采用引用计数(与java类似),为0时候由gc自动调用析构。

&创建一个影子(别名)引用,并不增加引用计数。

<?php
class NBAPlayer {
	public $name;
	public $height;
	public $weight;
	public $team;
	public $teamNumber;

	function __construct($name,$height,$weight,$team,$teamNumber){
		$this->name = $name;
		$this->height = $height;
		$this->weight = $weight;
		$this->team = $team;
		$this->teamNumber = $teamNumber;
		echo "construc a instance:".$name."<br/>";
	}
	function __destruct(){
		echo "Destroy a instance:".$this->name."<br/>";
	}
}
$jordan = new NBAPlayer("jordan","198cm","98kg","bull","23");
$james = new NBAPlayer("james","205cm","120kg","heat","10");
$james1 = $james;//相当于为james对象创建了一个新的引用
$james2 = &$james1;//创建一个影子引用,其实是一个别名
$james = null;
echo "james1 has not yet set to be nulled <br/>";
$james1 = null;//james对象调用析构(其引用计数已经为0)
echo "james1 has set to be nulled<br/>";

?>

运行结果:


construc a instance:jordan
construc a instance:james
james1 has not yet set to be nulled 
Destroy a instance:james
james1 has set to be nulled 
Destroy a instance:jordan



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值