轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 8109|回复: 1
打印 上一主题 下一主题

php类自动装载和php链式操作的原理

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-6-14 03:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本文主要和大家分享php类自动装载和php链式操作的原理,希望能帮助到大家。

1、自动装载实例

目录下有3个文件:index.php load.php tests文件夹

tests文件夹里有 test1.php


<?php
namespace Tests;
class Test1{
  static function test(){
    echo __CLASS__.'<br>';
    echo __FILE__.'<br>';
  }
}

index.php内容


<?php
include "load.php";
TestsTest1::test();

load.php内容


<?php
class 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();


分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

13

帖子

41

积分

新手上路

Rank: 1

积分
41
沙发
发表于 2022-10-21 09:58 来自手机 | 只看该作者
制作音乐的软件app
回复

使用道具 举报

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表