本文主要和大家分享php類自動裝載和php鏈式操作的原理,希望能協助到大家。
1、自動裝載執行個體
目錄下有3個檔案:index.php load.php tests檔案夾
tests檔案夾裡有 test1.php
<?phpnamespace Tests;class Test1{ static function test(){ echo __CLASS__.'<br>'; echo __FILE__.'<br>'; }}
index.php內容
<?phpinclude "load.php";Tests\Test1::test();
load.php內容
<?phpclass Loader{ static function loadClass($class) { $class = __DIR__.DIRECTORY_SEPARATOR.str_replace('\\','/',$class).'.php'; if (file_exists($class)) { include $class; return; } }}spl_autoload_register(array('Loader','loadClass'));
2.鏈式操作原理
在一個類中有多個方法,當你執行個體化這個類,並調用方法時只能一個一個調用,類似:
db.php
<?php class db{ public function where() { //code here } public function order() { //code here } public function limit() { //code here }}
index.php
<?php $db = new db(); $db->where();$db->order();$db->limit();
如果要實現鏈式調用,這要在方法的結束添加return $this即可。
db.php
<?php class db{ public function where() { //code here return $this; } public function order() { //code here return $this; } public function limit() { //code here return $this; }}
index.php
<?php $db = new db(); $db->where()->order()->limit();