时间:2021-07-01 10:21:17 帮助过:8人阅读
静态方法和非静态方法之间有一个很重要的区别,就是在调用静态方法时,我们不需要创建类的实例。
用类名作为参数可以解决非继承的静态问题。
程序运行结果:
I'm Apple
在派生类重写基类的方法。
程序运行结果:
Apple's color is red
静态和const作用域都可以用::操作符访问,如果你想使用::操作符访问数组,你需要事先将数组声明为静态。
'red', 'color2' => 'yellow');
}
class Apple
{
public function __construct()
{
var_dump(Fruit::$color);
}
}
class Banana
{
public function __construct()
{
Fruit::$color = FALSE;
}
}
new Apple(); // prints array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" }
echo '
';
new Banana();
new Apple(); // prints bool(false)
?>
程序运行结果:
array(2) { ["color1"]=> string(3) "red" ["color2"]=> string(6) "yellow" }
bool(false)
Static真的很酷,下面的程序演示了如何获得一个已经存在的实例。
value = $value;
}
public static function getInstance() {
if ( self::$instance == null ) {
echo "
new
";
self::$instance = new Singleton("values");
}
else {
echo "
old
";
}
return self::$instance;
}
}
$x = Singleton::getInstance();
var_dump($x); // returns the new object
$y = Singleton::getInstance();
var_dump($y); // returns the existing object
?>
程序运行结果:
new
object(Singleton)#1 (1) { ["value:private"]=> string(6) "values" }
old
object(Singleton)#1 (1) { ["value:private"]=> string(6) "values" }
http://www.bkjia.com/PHPjc/752389.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752389.htmlTechArticle静态方法的规则和静态变量是相同的。使用ststic关键字可以将方法标识为静态方法,通过类的名称和作用域限定操作符::可以访问静态方法...