php類自動裝載和php鏈式操作的原理

來源:互聯網
上載者:User
本文主要和大家分享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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.