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中文網其他相關文章!