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中文网其他相关文章!