


PHP namespace autoloading: How to use composer's autoload to achieve automatic loading
在 PHP5 以后的版本中可以定义一个 __autoload() 函数,当调用一个未定义的类的时候就会启动此函数,从而在抛出错误之前做最后的补救,不过这个函数的本意已经被完全曲解使用了,现在都用来做自动加载。后来这个函数实际上已经不被推荐使用了,相反,现在应当使用 spl_autoload_register() 来注册类的自动加载函数。前面我们介绍了php命名空间的基本知识,使用方法,作用等等,这一节就重点来说说php命名空间自动加载。
spl_autoload_register() 的语法格式如下:
bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )
autoload_function 是需要注册的自动装载函数,如果此项为空,则会注册 spl_autoload 函数,
throw 此参数设置了 autoload_function 无法成功注册时, spl_autoload_register() 是否抛出异常。
prepend 如果是 true, spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。
上面提到了 spl_autoload 函数,实际上注册函数的规范就应当遵循此函数,函数声明如下:
void spl_autoload ( string $class_name [, string $file_extensions ] )
由于这个函数默认实现是通过 C 语言,所以这里给出一个 PHP 语言的实现规范。
其实例代码如下:
<?php // 自定义类 define('CLASS_DIR', 'class/'); // 添加类的路径 set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR); // 使用自动加载添加类 spl_autoload_extensions('.class.php'); // 默认加载 spl_autoload_register(); ?>
大致上就和这个是类似的。实际上命名空间和自动加载类的结合就基本是通过路径形式。
使用composer的autoload来自动加载
composer的出现真是让人们眼前一亮,web开发从此变成了一件很“好玩”的事情,开发一个CMS就像在搭积木,从packagist中取出“ 积木 ”搭建在自己的代码中,一点一点搭建出一个属于自己的王国。
使用composer基本就可以抛弃了require和include函数,一个项目中,这两个函数只可能出现一次,那就是 require '../vendor/autoload.php'。
然后就可以非常方便的去使用第三方的类库了,是不是感觉很棒啊!对于我们需要的monolog,就可以这样用了:
use Monolog\Logger; use Monolog\Handler\StreamHandler; // 创建日志 $log = new Logger('name'); $log->pushHandler(new StreamHandler('/path/to/log/log_name.log', Logger::WARNING)); // 将记录添加到日志 $log->addWarning('Foo'); $log->addError('Bar');
在这个过程中,Composer做了什么呢?它生成了一个autoloader,再根据各个包自己的autoload配置,从而帮我们进行自动加载的工作。
实现方式的步骤:
1. 先安装composer,可以参照php依赖管理工具composer入门教程
2. 在项目根目录创建composer.json文件,写入代码
{ "type": "project", "autoload": { "psr-4": { "Admin\\": "admin/" } } }
3. 在项目根目录打开命令,写入命令
composer update
4.等待执行完成。安装成功后,会在项目根目录下新建一个"/vendor/"文件夹。
说明:使用之前需要require一下"/vendor/autoload.php"文件。
$autoLoadFilePath = dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php'; require_once $autoLoadFilePath;
5. 在"/admin/"目录下新建test.php文件,文件内容如下
<?php namespace Admin; class test { public function sayHi() { echo 'hi'; } } ?>
在"/public/"目录下新建index.php文件,文件内容如下
sayHi(); ?>
6. 配置apache,访问路径,得到如下的结果就表示成功。
【相关教程推荐】
2. 视频教程:命名空间:我们虽然同名同性,但却属于不同时空
The above is the detailed content of PHP namespace autoloading: How to use composer's autoload to achieve automatic loading. For more information, please follow other related articles on the PHP Chinese website!

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment