一:PHP实例的比较
- == :当使用比较操作符(==)时,对象以一种很简单的规则比较:当两个对象有相同的属性和值,属于同一个类且被定义在相同的命名空间中,则两个对象相等。
$p = new Person();
$p1 = new Person();
//比较对象
if ($p == $p1) {
echo "/$p和/$p1内容一致";
} else {
echo "/$p和/$p1内容不一致";
}
echo "<br />";
$p->name = "Tom";
if ($p == $p1) {
echo "/$p和/$p1内容一致";
} else {
echo "/$p和/$p1内容不一致";
}
2. ===: 当使用全等符(===)时,当且仅当两个对象指向相同类(在某一特定的命名空间中)的同一个对象时才相等。是否在是同一个对象,两边指向的对象是否有同样的内存地址。
二 析构函数
当创建一个对象后,PHP中没有任何变量指向这个对象,那么就会运行析构函数: public function __destruct()
unset()用于销毁指向这个对象的变量。
class p{
public function __destruct(){}
}
$p1 = new p();
$p2 = $p1;
unset($p1);//不执行析构函数
unset($p2);//执行了析构函数
三 static的用法
static关键字用来修饰属性、方法,称这些属性、方法为静态属性、静态方法。
static最常用的就是通过::直接访问类
实例化后。static的属性和方法在内存中只占有一个地址。实例之间共享这个地址。
例:计数器(静态属性)
<?php
class user
{
private static $count = 0 ;
public function __construct() {
self::
$count = self::$count + 1;
}
public function getCount() {
return self::$count;
}
public function __destruct() {
self::
$count = self::$count - 1;
}
}
$user1 = new user();
$user2 = new user();
$user3 = new user();
echo "now here have " . $user1->getCount() . " user";
echo "<br />";
unset($user3);
echo "now here have " . $user1->getCount() . " user";
?>
class user
{
private static $count = 0 ;
public function __construct() {
self::
$count = self::$count + 1;
}
public function getCount() {
return self::$count;
}
public function __destruct() {
self::
$count = self::$count - 1;
}
}
$user1 = new user();
$user2 = new user();
$user3 = new user();
echo "now here have " . $user1->getCount() . " user";
echo "<br />";
unset($user3);
echo "now here have " . $user1->getCount() . " user";
?>
class user
{
private static $count = 0 ;
public function __construct() {
self::
$count = self::$count + 1;
}
public function getCount() {
return self::$count;
}
public function __destruct() {
self::
$count = self::$count - 1;
}
}
$user1 = new user();
$user2 = new user();
$user3 = new user();
echo "now here have " . $user1->getCount() . " user";
echo "<br />";
unset($user3);
echo "now here have " . $user1->getCount() . " user";
?>
当一个类中有非静态方法被self:: 调用时,系统会自动将这个方法转换为静态方法。
<?php
class Math
{
public function Max($num1, $num2) {
return $num1 > $num2 ? $num1 : $num2;
}
public static function Max3($num1, $num2, $num3) {
$num1 = self::Max($num1, $num2);
$num2 = self::Max($num2, $num3);
$num1 = self::Max($num1, $num2);
return $num1;
}
}
$a = 99;
$b = 77;
$c = 188;
echo "show $a $b $c biggest one";
echo "<br />";
echo Math::Max3($a, $b, $c);
?>