【PHP】类和对象

来源:互联网 发布:java 弱引用 gc 编辑:程序博客网 时间:2024/06/05 11:22

一、类和对象

1、第一个类

class ShopProduct{    private $id = 1;    public $title = "product title 1";    public $price = 100;}
$product1 = new ShopProduct();echo $product1->title;$product1->title = "new title";echo $product1->title;

2、使用类的方法

class ShopProduct{    private $id = 1;    public $title = "product title 1";    public $price = 100;        function __construct($title,$price){        $this->title = $title;        $this->price = $price;    }    function printInfo(){        echo $this->title;        echo $this->price;    }}
在上例中把类的初始化功能集成到类中,以减少代码的重复。当使用new操作符创建对象时,__construct()方法会被调用。(PHP4不会把__construct()方法当做构造函数)

3、类的继承

class CDProduct extends ShopProduct{    public $length;    function __construct($title,$price,$length){        parent::__construct($title,$price);        $this->length = $length;    }}

4、以上所有例子使用的都是对象,我们通过把类生成的对象作为活动组件,进行对象方法的调用。不过,我们不仅仅可以通过对象访问方法和属性,还可以通过类来访问它们,这样的方法和属性石“静态的”(static),必须使用static关键字来声明。

class Car{    static public $carPrice;    static public $numberOfSell;    static public function carSold(){        self::$numberOfSell ++;    }}
echo Car::$carPrice;Car::carSold();


0 0
原创粉丝点击