php手记-获得文件或文件夹的上级目录、spl_autoload_register、__autoload

获得文件或文件夹的上级目录

//__FILE__:/home/sakurallj/personDoc/phpWorkspace/fastRoute/vendor/composer/autoload_psr4.php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
var_dump($vendorDir,$baseDir,dirname($baseDir)) ;

//---output----
string(82) "/home/sakurallj/personDoc/phpWorkspace/fastRoute/vendor/composer/autoload_psr4.php"
string(55) "/home/sakurallj/personDoc/phpWorkspace/fastRoute/vendor"
string(48) "/home/sakurallj/personDoc/phpWorkspace/fastRoute"
string(38) "/home/sakurallj/personDoc/phpWorkspace"

自动加载spl_autoload_register、__autoload

为什么要自动加载

<?php
//如果没有自动加载,那么在使用相应类的时候就要像下面一样写一大堆include_once、require等
include_once("./myClass.php");
include_once("./myFoo.php");
include_once("./myBar.php");

$obj = new myClass();
$foo = new Foo();
$bar = new Bar();
?>

__autoload()

作用

尝试加载未定义的类,当在new class时,如果找不到class则会自动去执行__autoload()

用法

./myClass.php
<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function __autoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}

// we've called a class ***
$obj = new myClass();//new时发现myClass没有被定义,则调用__autoload把类定义加载进来
?>

spl_autoload_register(function)

作用

告诉PHP碰到没有定义的类就执行function()

用法

./myClass.php
<?php
class myClass {
    public function __construct() {
        echo "myClass init'ed successfuly!!!";
    }
}
?>

./index.php
<?php
// we've writen this code where we need
function myAutoload($classname) {
    $filename = "./". $classname .".php";
    include_once($filename);
}
spl_autoload_register( 'myAutoload' );
// we've called a class ***
$obj = new myClass();//new时发现myClass没有被定义,则调用myAutoload把类定义加载进来
?>

spl_autoload_register、__autoload区别

这里写代码片

参考

http://blog.csdn.net/panpan639944806/article/details/23192267
http://www.php.net/manual/en/function.spl-autoload-register.php
http://www.php.net/manual/zh/function.autoload.php

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值