当前位置:Gxlcms > PHP教程 > 讲解PHP类初始化功能代码

讲解PHP类初始化功能代码

时间:2021-07-01 10:21:17 帮助过:19人阅读

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类初始化功能代码的内容,更多相关知识请关注Gxl网。

相关推荐:

讲解PHP面向对象,PHP继承相关代码

讲解PHP面向对象序列化、反序列化的相关代码

如何通过PHP方法判断是否是手机登录(代码)

以上就是讲解PHP类初始化功能代码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行