類的成員:
1.常數 : const 常數名稱 = 值;
2.屬性
2.1 靜態屬性
2.2 實例屬性
3.方法
3.1靜態方法
3.2實例方法
3.3構造方法
3.4析構方法
注意:
①靜態屬性是屬於類別的,透過這個類別建立的物件共用此屬性
②實例方法中可以使用靜態屬性和靜態方法
③靜態方法中不可以存取實例屬性和實例方法,因為靜態的都是屬於類別的,實例的屬於對象,類別在的時候對象還沒new出來!
<code><span><span><?php</span>header(<span>"content-type:text/html;charset=utf-8"</span>); <span><span>class</span><span>C</span>{</span><span>const</span> PATH = <span>"C:/windows"</span>;<span>//类中不能使用 define定义常量</span><span>//静态属性</span><span>static</span><span>$count</span> = <span>66</span>;<span>//等价于 static public $count = 66;</span><span>//实例属性</span><span>public</span><span>$name</span> = <span>"tom"</span>;<span>//等价于 var $name = "tom";</span><span>//默认的无参构造函数</span><span>//function __construct(){</span><span>//</span><span>// echo "<br> __construct 无参构造方法被调用";</span><span>//}</span><span>//有参构造函数,一般用来类成员属性的初始化,php中一个类只能存在一个构造方法</span><span><span>function</span><span>__construct</span><span>(<span>$name</span>)</span>{</span><span>$this</span>->name = <span>$name</span>; <span>echo</span><span>"<br> __construct 有参构造方法被调用"</span>; } <span>//实例方法</span><span><span>function</span><span>instanceFun</span><span>()</span>{</span><span>echo</span><span>"<br>实例方法被调用"</span>; <span>echo</span><span>"<br>实例方法中访问常量:"</span>.<span>self</span>::PATH; <span>echo</span><span>"<br>实例方法中访问实例属性:{$this->name}"</span>; <span>echo</span><span>"<br>实例方法中访问静态属性:"</span>.<span>self</span>::<span>$count</span>;<span>//self就代表类本身</span><span>//实例方法中调用静态方法</span><span>self</span>::staticFun(); } <span>//静态方法</span><span>static</span><span><span>function</span><span>staticFun</span><span>()</span>{</span><span>echo</span><span>"<br>静态方法被调用"</span>; <span>echo</span><span>"<br>静态方法中访问常量:"</span>.<span>self</span>::PATH; <span>echo</span><span>"<br>静态方法中访问静态属性:"</span>.<span>self</span>::<span>$count</span>; <span>//注意:静态方法中无法访问实例属性</span>} <span>//析构方法,当对象被销毁的时候由系统去调用</span><span>//通常代码执行完,对象就会被销毁</span><span><span>function</span><span>__destruct</span><span>()</span>{</span><span>echo</span><span>"<br>对象 {$this->name} 被销毁"</span>; } } <span>$object</span> = <span>new</span> C(<span>"哈利波特"</span>); <span>$object</span>->instanceFun(); <span>echo</span><span>"<hr>"</span>; C::staticFun(); <span>//下面代码会使$object指向的对象被销毁</span><span>//$object = null;</span><span>//$object = new C("秦始皇");;</span><span>//$object = 3;</span><span>//unset($object);</span><span>echo</span><span>"<br>程序最后一行代码。。。"</span>;</span></code>
以上就介紹了php物件導向之類成員,包括了物件導向,php方面的內容,希望對PHP教學有興趣的朋友有幫助。