講解PHP類初始化功能代碼

來源:互聯網
上載者:User
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中文網。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.