首頁 >後端開發 >php教程 >講解PHP類別初始化功能碼

講解PHP類別初始化功能碼

jacklove
jacklove原創
2018-06-08 14:22:514749瀏覽

PHP類別初始化功能在php中有著重要的作用,本篇文章將詳解其相關程式碼的內容。

<!--?php
    class ShopProduct {
        public $title = "default product";
        public $producerMainName = "main name";
        public $producerFirstName = "first name";
        public $price = 0;
        function getProducer() {
            return "{$this--->producerFirstName}" . " {$this->producerMainName}";
        }
    $product1 = new ShopProduct();
    $product1->title = "My Antonia";
    $product1->producerMainName = "Cather";
    $product1->producerFirstName = "Willa";
    $product1->price = 5.99;
    print "author: {$product1->getProducer()}";
>
<!--?php  
    class ShopProduct {
        public $title;
        public $producerMainName;
        public $producerFirstName;
        public $price = 0;
        function __construct($title,$firstName,$mainName,$price) { //构造方法
            $this--->title = $title;
            $this->producerFirstName = $firstName;
            $this->producerMainName = $mainName;
            $this->price = $price;
        }
        function getProducer() {
            return "{$this->producerFirstName}" . " {$this->producerMainName}";
        }
    }
    $product1 = new ShopProduct( "My Antionia", "willa", "Cather", 5.99);
    print "author: {$product1->getProducer()}";
>

上面把先前的初始化功能整合到類別中,以減少程式碼的重複。當使用new操作符建立物件時,__construct()方法會被呼叫。

本篇文章說明了PHP類別初始化功能程式碼的內容,更多相關知識請關注php中文網。

相關推薦:

解說PHP物件導向,PHP繼承相關程式碼

解說PHP物件導向序列化、反序列化的相關代碼

如何透過PHP方法判斷是否為手機登入(代碼)

以上是講解PHP類別初始化功能碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn