php 实现类,PHP 实现类的自动加载

本文介绍了如何使用PHP的spl_autoload_register函数来实现类的自动加载,避免了在每个文件顶部手动require或include。通过创建一个自定义的类Autoloader,注册到自动加载队列中,当尝试实例化未定义的类时,会自动调用loader方法加载对应的类文件。这种方法使得类加载更加高效和有序,同时也支持多个自动加载函数的注册。
摘要由CSDN通过智能技术生成

使用 spl_autoload_register() 函数实现类的自动加载

一个文件中,往往需要使用多个别的类。这种情况下,一般是必须先在文件顶部使用 require/require_once或 include_include_once 进行加载,才能实例函数。

使用 spl_auto_register() 实现自加载的执行过程输出:

Trying to loadClass1 via ClassAutoloader::loader()

Class1::__construct

Trying to loadClass2 via Class

Autoloader::loader() Class2::__construct

spl_autoload_register - Register given function as __autoload() implementation

Description

bool spl_autoload_register([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]])

Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated.

If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue. This is because spl_autoload_register()

will efectively replace the engine cache for the __autoload() function by either spl_autoload() or spl_autoload_call().

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of

them in the order they are defined. By contrast, __autoload() may only be defined once.

目录结构:

modernphp/ClasssAutoloader.php

modernphp/Class1.php

mordernphp/Class2.php

ClassAutokloader.php

class ClassAutoloader

{

public function __construct() {

spl_autoload_register(array($this, 'loader'));

}

public function loader($className) {

echo "Trying to load" , $className, ' via ', __METHOD__, "()\n";

echo "
";

include $className . '.php';

}

}

$autoloader = new ClassAutoloader();

$obj = new Class1();

$obj = new Class2();

Class1.php

class Class1

{

public function __construct()

{

echo __METHOD__;

echo "
";

}

}

Class2.php

class Class1

{

public function __construct()

{

echo __METHOD__;

echo "
";

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值