Table of Contents
Preface
Component-based development
Namespace
Name conflict
重命名与访问控制
其他
总结
Home PHP Framework Laravel Summarize what PHP syntax is commonly used in Laravel

Summarize what PHP syntax is commonly used in Laravel

Sep 09, 2021 am 11:28 AM
laravel php

Preface

Laravel frameworkBecause of its componentized design and proper use of design Patterns make the framework itself concise and easy to extend. Different from ThinkPHP's integrated function framework (either all functions are used or none), Laravel uses the composer tool to manage packages. If you want to add functions, you can directly add components. For example, if you write a crawler and use the page collection component: composer require jaeger/querylist

This article briefly introduces the PHP features and new syntax frequently used in Laravel. Please refer to it for details.

Component-based development

Laravel performs component-based development thanks to the composer tool that follows the PSR-4 specification, which uses namespaces and automatic loading to organize project files. More reference: composer automatic loading mechanism

Namespace

Name conflict

When collaborating in a team and introducing third-party dependent code, classes, functions and interfaces may often appear Duplicate names. For example:

<?php     
# google.php
class User 
{
    private $name;
}
Copy after login
<?php     
# mine.php
// 引入第三方依赖
include &#39;google.php&#39;;

class User
{
    private $name;
}

$user = new User();    // 命名冲突
Copy after login

Name conflict occurs because the class User is defined at the same time:

Summarize what PHP syntax is commonly used in Laravel

##Solution

From PHP 5.3 Start the introduction. Refer to the PHP manual to know that namespace has two functions: to avoid

naming conflicts and to keep names short. For example, after using the namespace:

<?php # google.php
namespace Google;

// 模拟第三方依赖
class User {
    private $name = &#39;google&#39;;

    public function getName() {
        echo $this->name . PHP_EOL;
    }
}
Copy after login
<?php # mine.php
namespace Mine;

// 导入并命名别名
use Google as G;

// 导入文件使得 google.php 命名空间变为 mine.php 的子命名空间
include &#39;google.php&#39;;

/* 避免了命名冲突 */
class User
{
    private $name = &#39;mine&#39;;

    public function getName() {
        echo $this->name . PHP_EOL;
    }
}

/* 保持了命名简短 */
// 如果没有命名空间,为了类名也不冲突,可能会出现这种函数名
// $user = new Google_User();
// Zend 风格并不提倡
$user = new G\User();

// 为了函数名也不冲突,可能会出现这种函数名
// $user->google_get_name()
$user->getName();

$user = new User();
$user->getName();
Copy after login
Run:

$ php demo.php
google
mine
Copy after login
PSR specification

In fact, the namespace has nothing to do with the file name, but according to the PSR standard requirements: the namespace is consistent with the file path& The file name is consistent with the class name. For example,

laravel-demo/app/Http/Controllers/Auth/LoginController.php generated by Laravel by default, its namespace is App\Http\Controllers\Auth & class name LoginController

Follow the specifications, the above

mine.php and google.php should both be called User.php

namespace operator and

__NAMESPACE__ Magic constants
...
// $user = new User();
$user = new namespace\User();    // 值为当前命名空间
$user->getName();

echo __NAMESPACE__ . PHP_EOL;    // 直接获取当前命名空间字符串    // 输出 Mine
Copy after login

Import of three namespaces

<?php namespace CurrentNameSpace;

// 不包含前缀
$user = new User();        # CurrentNameSpace\User();

// 指定前缀
$user = new Google\User();    # CurrentNameSpace\Google\User();

// 根前缀
$user = new \Google\User();    # \Google\User();
Copy after login

Global namespace

If the referenced class, If the function does not specify a namespace, it will be searched under

__NAMESPACE__ by default. To reference the global class:

<?php namespace Demo;

// 均不会被使用到
function strlen() {}
const INI_ALL = 3;
class Exception {}

$a = \strlen(&#39;hi&#39;);         // 调用全局函数 strlen
$b = \CREDITS_GROUP;          // 访问全局常量 CREDITS_GROUP
$c = new \Exception(&#39;error&#39;);   // 实例化全局类 Exception
Copy after login
Multiple imports and multiple namespaces

// use 可一次导入多个命名空间
use Google,
    Microsoft;

// 良好实践:每行一个 use
use Google;
use Microsoft;
Copy after login
<?php // 一个文件可定义多个命名空间
namespace Google {
    class User {}
}    
    
namespace Microsoft {
    class User {}
}   

// 良好实践:“一个文件一个类”
Copy after login

Import constants and functions

Starting from PHP 5.6, you can use

use function and use const Import functions and constants respectively. Use:

# google.php
const CEO = 'Sundar Pichai';
function getMarketValue() {
    echo '770 billion dollars' . PHP_EOL;
}
Copy after login
# mine.php
use function Google\getMarketValue as thirdMarketValue;
use const Google\CEO as third_CEO;

thirdMarketValue();
echo third_CEO;
Copy after login
Run:

$ php mine.php
google
770 billion dollars
Sundar Pichaimine
Mine
Copy after login
File contains

Manual loading

Use

include or require to introduce the specified file. (Literal interpretation) Please note that a require error will report a compilation error and interrupt the script, while an include error will only report a warning and the script will continue to run.

include file, it will first search in the directory specified by the configuration item

include_path in php.ini. If it cannot find it, it will search in the current directory:

Summarize what PHP syntax is commonly used in Laravel

<?php     
// 引入的是 /usr/share/php/System.php
include &#39;System.php&#39;;
Copy after login
Automatic loading

void __autoload(string $class) can automatically load classes, but generally use spl_autoload_register to register manually:

<?php // 自动加载子目录 classes 下 *.class.php 的类定义
function __autoload($class) {
    include &#39;classes/&#39; . $class . &#39;.class.php&#39;;
}

// PHP 5.3 后直接使用匿名函数注册
$throw = true;        // 注册出错时是否抛出异常
$prepend = false;    // 是否将当前注册函数添加到队列头

spl_autoload_register(function ($class) {
    include &#39;classes/&#39; . $class . &#39;.class.php&#39;;
}, $throw, $prepend);
Copy after login
In the autoloading file generated by composer

laravel-demo/vendor/composer/autoload_real.php you can see:

class ComposerAutoloaderInit8b41a
{
    private static $loader;

    public static function loadClassLoader($class)
    {
        if ('Composer\Autoload\ClassLoader' === $class) {
            // 加载当前目录下文件
            require __DIR__ . '/ClassLoader.php';
        }
    }
    
     public static function getLoader()
    {
        if (null !== self::$loader) {
            return self::$loader;
        }
    
        // 注册自己的加载器
        spl_autoload_register(array('ComposerAutoloaderInit8b41a6', 'loadClassLoader'), true, true);
        self::$loader = $loader = new \Composer\Autoload\ClassLoader();
        spl_autoload_unregister(array('ComposerAutoloaderInit8b41a6a', 'loadClassLoader'));

        ...
     }
 
    ...
}
Copy after login
I will only mention here, specifically how Laravel does automatic loading as a whole Yes, the following articles will elaborate on it.

Reflection

Refer to the PHP manual, which can be simply understood as obtaining the complete information of the object at runtime. There are 5 classes of reflection:

ReflectionClass     // 解析类名
ReflectionProperty     // 获取和设置类属性的信息(属性名和值、注释、访问权限)
ReflectionMethod     // 获取和设置类函数的信息(函数名、注释、访问权限)、执行函数等
ReflectionParameter    // 获取函数的参数信息
ReflectionFunction    // 获取函数信息
Copy after login
For example, the use of

ReflectionClass:

<?php class User
{
    public $name;
    public $age;

    public function __construct($name = &#39;Laruence&#39;, $age = 35) {
        $this->name = $name;
        $this->age  = $age;
    }

    public function intro() {
        echo '[name]: ' . $this->name . PHP_EOL;
        echo '[age]: '  . $this->age  . PHP_EOL;
    }
}

reflect('User');

// ReflectionClass 反射类使用示例
function reflect($class) {
    try {
        $ref = new ReflectionClass($class);
        // 检查是否可实例化
        // interface、abstract class、 __construct() 为 private 的类均不可实例化
        if (!$ref->isInstantiable()) {
            echo "[can't instantiable]: ${class}\n";
        }

        // 输出属性列表
        // 还能获取方法列表、静态常量等信息,具体参考手册
        foreach ($ref->getProperties() as $attr) {
            echo $attr->getName() . PHP_EOL;
        }

        // 直接调用类中的方法,个人认为这是反射最好用的地方
        $obj = $ref->newInstanceArgs();
        $obj->intro();
    } catch (ReflectionException $e) {
            // try catch 机制真的不优雅
            // 相比之下 Golang 的错误处理虽然繁琐,但很简洁
        echo '[reflection exception: ]' . $e->getMessage();
    }
}
Copy after login
Run:

$ php reflect.php
name
age
[name]: Laruence
[age]: 35
Copy after login
For the other four reflection classes, please refer to the manual demo .

Late static binding

Refer to the PHP manual and look at an example first:

<?php class Base
{
        // 后期绑定不局限于 static 方法
    public static function call() {
        echo &#39;[called]: &#39; . __CLASS__ . PHP_EOL;
    }

    public static function test() {
        self::call();        // self   取值为 Base  直接调用本类中的函数
        static::call();        // static 取值为 Child 调用者
    }
}

class Child extends Base
{
    public static function call() {
        echo &#39;[called]: &#39; . __CLASS__ . PHP_EOL;
    }
}


Child::test();
Copy after login
Output:

$ php late_static_bind.php
[called]: Base
[called]: Child
Copy after login
When the object is instantiated,

self:: will instantiate the class in which it is defined, static:: will instantiate the class that calls it.

trait

Basic usage

Refer to the PHP manual. Although PHP is single-inherited, from 5.4 onwards, "classes" can be realized by horizontally combining "classes" through traits. Multiple inheritance is actually to split the repeated functions into triats and put them in different files, and introduce and combine them as needed through the use keyword. Inheritance can be implemented by analogy to Golang's struct cramming combination. For example:

<?php class DemoLogger
{
    public function log($message, $level) {
        echo "[message]: $message", PHP_EOL;
        echo "[level]: $level", PHP_EOL;
    }
}

trait Loggable
{
    protected $logger;

    public function setLogger($logger) {
        $this->logger = $logger;
    }

    public function log($message, $level) {
        $this->logger->log($message, $level);
    }
}

class Foo
{
        // 直接引入 Loggable 的代码片段
    use Loggable;
}

$foo = new Foo;
$foo->setLogger(new DemoLogger);
$foo->log('trait works', 1);
Copy after login
Run:

$ php trait.php
[message]: trait works
[level]: 1
Copy after login
More reference: What I understand about PHP Trait

Important properties

Priority

The function of the current class will overwrite the function of the same name of the trait, and the trait will overwrite the function of the same name of the parent class (

use trait is equivalent to the current class directly overwriting the function of the same name of the parent class)

trait function Conflict

Introduction of multiple traits at the same time can be separated by

,, that is, multiple inheritance.

多个 trait 有同名函数时,引入将发生命名冲突,使用 insteadof 来指明使用哪个 trait 的函数。

重命名与访问控制

使用 as 关键字可以重命名的 trait 中引入的函数,还可以修改其访问权限。

其他

trait 类似于类,可以定义属性、方法、抽象方法、静态方法和静态属性。

下边的苹果、微软和 Linux 的小栗子来说明:

<?php trait Apple
{
    public function getCEO() {
        echo &#39;[Apple CEO]: Tim Cook&#39;, PHP_EOL;
    }

    public function getMarketValue() {
        echo &#39;[Apple Market Value]: 953 billion&#39;, PHP_EOL;
    }
}


trait MicroSoft
{
    public function getCEO() {
        echo &#39;[MicroSoft CEO]: Satya Nadella&#39;, PHP_EOL;
    }

    public function getMarketValue() {
        echo &#39;[MicroSoft Market Value]: 780 billion&#39;, PHP_EOL;
    }

    abstract public function MadeGreatOS();

    static public function staticFunc() {
        echo &#39;[MicroSoft Static Function]&#39;, PHP_EOL;
    }

    public function staticValue() {
        static $v;
        $v++;
        echo &#39;[MicroSoft Static Value]: &#39; . $v, PHP_EOL;
    }
}


// Apple 最终登顶,成为第一家市值超万亿美元的企业
trait Top
{
    // 处理引入的 trait 之间的冲突
    use Apple, MicroSoft {
        Apple::getCEO insteadof MicroSoft;
        Apple::getMarketValue insteadof MicroSoft;
    }
}


class Linux
{
    use Top {
            // as 关键字可以重命名函数、修改权限控制
        getCEO as private noCEO;
    }

    // 引入后必须实现抽象方法
    public function MadeGreatOS() {
        echo &#39;[Linux Already Made]&#39;, PHP_EOL;
    }

    public function getMarketValue() {
        echo &#39;[Linux Market Value]: Infinity&#39;, PHP_EOL;
    }
}

$linux = new Linux();
// 和 extends 继承一样
// 当前类中的同名函数也会覆盖 trait 中的函数
$linux->getMarketValue();

// trait 中可以定义静态方法
$linux::staticFunc();

// 在 trait Top 中已解决过冲突,输出库克
$linux->getCEO();
// $linux->noCEO();        // Uncaught Error: Call to private method Linux::noCEO() 

// trait 中可以定义静态变量
$linux->staticValue();
$linux->staticValue();
Copy after login

运行:

$ php trait.php
[Linux Market Value]: Infinity
[MicroSoft Static Function]
[Apple CEO]: Tim Cook
[MicroSoft Static Value]: 1
[MicroSoft Static Value]: 2
Copy after login

总结

本节简要提及了命名空间、文件自动加载、反射机制与 trait 等,Laravel 正是恰如其分的利用了这些新特性,才实现了组件化开发、服务加载等优雅的特性。

The above is the detailed content of Summarize what PHP syntax is commonly used in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Laravel vs. Python (with Frameworks): A Comparative Analysis Laravel vs. Python (with Frameworks): A Comparative Analysis Apr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Using Laravel: Streamlining Web Development with PHP Using Laravel: Streamlining Web Development with PHP Apr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

What database versions are compatible with the latest Laravel? What database versions are compatible with the latest Laravel? Apr 25, 2025 am 12:25 AM

The latest version of Laravel10 is compatible with MySQL 5.7 and above, PostgreSQL 9.6 and above, SQLite 3.8.8 and above, SQLServer 2017 and above. These versions are chosen because they support Laravel's ORM features, such as the JSON data type of MySQL5.7, which improves query and storage efficiency.

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

See all articles