首页 >后端开发 >php教程 >讲解PHP类初始化功能代码

讲解PHP类初始化功能代码

jacklove
jacklove原创
2018-06-08 14:22:514748浏览

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