Home >Backend Development >PHP Tutorial >php-object-oriented (3)

php-object-oriented (3)

WBOY
WBOYOriginal
2016-08-08 09:19:25809browse

1. Review: In the previous article, I learned PHP’s inheritance, properties and static properties

2. In this article, I will learn PHP’s class constants, autoloading classes, constructors and destructors

3. Classes Constants

<span> (1)常量的值始终不变,在定义和使用常量的时候不需要使用$符号
 (2)接口(interface)中也可以定义常量</span>
<pre name="code">#定义和使用一个类常量
     class aclass{
         const a="a 是常量";
         function showA(){
             echo self::a;
         }
     }
     
     echo aclass::a; //结果:a 是常量
     echo aclass::showA(); //结果:a 是常量

     $classname="aclass";
     echo $classname::a; //结果:a 是常量

     $ac=new aclass();
     $ac->showA(); //结果:a 是常量
    
     //PHP 5.3.0之后支持
     $ac::a;
4. Autoloading objects
<span></span><pre class="brush:php;toolbar:false"><span> (1)__autoload 函数,它会在试图使用尚未被定义的类时自动调用
 (2) 不需要使用过量的include
 (3)_autoload函数中抛出异常不能被catch捕获
 (4)如果使用phpCLI交互模式时,自动加载不存在</span>
<pre name="code">  function __autoload($cName){
       require_once $cName . 'php';
   }
    $d=new demo_aclass();
    $d->say();

5. Constructors
<span></span><pre class="brush:php;toolbar:false"><span> (1) __construct (args) 方法,实现构造函数
 (2)构造函数可以每次创建的时候,先调用此方法,完成初始化工作
 (3)子类中定义了构造函数不会自动调用父类构造函数
 (4)若执行父类构造函数,需要在子类中调用 parrent::_construct()</span>
<span></span>
<pre name="code">  class baseClass{

         function __construct(){
             echo "base construct";
         }
     }
     class subClass extends baseClass{
         function __construct(){
             parent::__construct();
             echo "sub construct";
         }
     }
     $bas=new baseClass();
     $sub=new subClass();

<span></span>
<span><span>6.析构函数</span></span>
<span></span>
 (1)void__destruct(void)
 (2)析构函数会在某个对象的所有引用都删除或者当对象被显示销毁时执行
 (3)和构造函数一样,不会自动调用,当子类在析构函数中显示调用时执行
 (4)parent::__destruct()
<span style="color:#46830d;"> </span> echo "<br>";
     class myClass{
         function __construct(){
             echo "construct 构造函数";
         }
         function __destruct(){
             echo "析构函数执行:".$this->name;
         }
     }
     $mc=new myClass();<span style="color:#46830d;">
</span>

<span>下篇将学习php-面向对象: <spanbitstream vera sans line-height:23.2000007629395px>访问控制</spanbitstream></span>
<span></span>

Copyright statement: This article is an original article by the blogger and has not been published by the blogger No reproduction allowed with permission of the owner.

The above introduces php-object-oriented (3), including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn