版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sdutphp/article/details/82556232
<?php
header("content-type:text/html;charset=utf-8");
echo '<pre>';
class Goods
{
public static $goods_name = '咖啡';
public $price = 9.90;
public static function get_goods_name()
{
echo self::$goods_name; //静态方法调用静态属性,使用self关键词
// Fatal error: Using $this when not in object context
// echo $this->price; //错误的用法。静态方法不能调用非静态属性,因为 $this代表实例化对象,而这里是类,不知道 $this代表哪个对象
echo "\n";
}
public function get_price()
{
echo self::$goods_name; //普通方法调用静态属性,同样使用self关键词
echo '【单价:】' . $this->price;
echo "\n";
}
}
$goods = new Goods();
$goods->get_price();
//对象可以访问静态方法
$goods->get_goods_name();
//对象访问静态属性。不能这么访问$goods->goods_name,因为静态属性的内存位置不在对象里
echo $goods::$goods_name;
echo "\n";
// Strict Standards: Non-static method Goods::get_price() should not be called statically
// Goods::get_price();//错误的用法。