Home Backend Development PHP Tutorial In-depth understanding of static and yield keywords in php

In-depth understanding of static and yield keywords in php

Sep 19, 2017 am 09:27 AM
php static yield

This article mainly introduces you to the relevant information about the static and yield keywords in PHP. The article introduces it in great detail through sample codes. It has certain reference learning value for everyone to learn or use PHP. Friends who need this article Let’s learn with the editor below.

Preface

This article mainly introduces the relevant content about the static and yield keywords in PHP, and shares it for your reference and study. Not much to say below, let’s take a look at the detailed introduction.

Let’s talk about the static keyword first. This article only talks about the use of static methods and late binding.

#static When to use it to modify methods

#static keyword Everyone knows that it is used to modify methods and properties. So in what scenarios do you use it in your projects?

I have encountered several projects that require all methods to be static. Of course, controller methods cannot do this. One of the reasons is: static method execution efficiency is high? So let's analyze it based on this.

First of all, I have no objection to the high execution efficiency. Is it because it is highly efficient that it should be used in projects without restraint? To discuss this issue, let’s first review the history of programming languages. In the early days, there was no object-oriented programming, and structured programming was used. At that time, basically all methods were static methods. Then object-oriented came into being, and the concept of instantiation came into being.

It can be seen from the brief development process above that if it is just for performance, there seems to be no need for object-oriented existence. So what do these masters think about introducing object-oriented and instantiation into languages ​​such as c++ and java? I think it's because with development, projects are getting bigger and bigger, requiring better organization of code and programming thinking.

Looking back at static, the static method it defines is indeed very efficient, but it will continue to occupy memory. The life cycle will only end when the program exits. One of the side effects is that it cannot be destroyed during the period; Secondly, from the design mode point of view, it has strong coupling, and the static attribute can be modified externally; thirdly, there is no way to override the method defined by static, and concepts such as ioc di are useless; fourthly, when performing unit testing, static methods Gives people a headache.

So based on the above, I feel that it is better not to use static methods in the future, but to instantiate and call methods honestly? We must be rational, and we cannot be so extreme that we use it everywhere, nor can we use it at all. Bottom line: Learn to think in an object-oriented way. I think the first consideration when we write code is: scalability (to cope with rapid business changes) and maintainability (to repair online problems in a timely manner). High efficiency should be considered last (because there are so many ways to optimize efficiency, it is not necessary to add: static to every method). If from an object-oriented perspective, this method is completely independent and has nothing to do with class attributes, then use static.

In short, we consider the use of syntax from an object-oriented perspective and the level of software design, rather than destroying the beauty of the code for efficiency.

static Late static binding

The PHP documentation introduces this in detail, but I have rarely paid attention to it before. This place basically uses self:: to call static methods and properties.

I think late binding is like overloading of static methods to some extent. Here is an example from the php document to describe it


<?php
class A {
 public static function who() {
 echo __CLASS__;
 }
 public static function test() {
 self::who();
 static::who();// 后期静态绑定
 }
}

class B extends A {
 public static function who() {
 echo __CLASS__;
 }
}

B::test();
Copy after login

If self::who() is called, it will output: A. If it is static::who(), it will output B

. From this point of view, is it equivalent to class B overriding the who() method of parent class A? So if you use this feature flexibly, you can make static more flexible. Give full play to its performance advantages and solve the problem of poor scalability. Of course, it's still the same. From an object-oriented perspective, everything is done in moderation.

Usage scenarios of yield in PHP

To be honest, I didn’t know that PHP had such a syntax for a long time . Until one day I encountered this keyword in js. I felt that it was such an unclear thing. Why is it not available in the best language in the world? Looking back at the documentation, I can see that it is indeed the best language in the world.

So what are the usage scenarios of yield? Someone on sg just recently asked me to sort it out. I hope everyone can use it more in conjunction with their own business. There is no comparison between yield and Iterator. I believe that after reading it, you will be able to understand which of the two is more brief.

先说它的使用场景,还是得先回顾历史,在没有 yield 之前,我们要生成一个数组,只能一次性把所有内容全部读入内存(当然也可以通过实现 Iterator接口实现一个迭代)。有了 yield 之后,我们可以通过一个简单的 yield 关键字,完成一个数组的生成,并且是用到的时候才会产生值,相对而言内存占用肯定会下降。空口无凭,咱们下面通过代码实际检验一下上面的结论。

先来看普通模式


<?php

function generateData($max)
{
 $arr = [];
 for ($i = 0; $i <= $max; $i++) {
 $arr[] = $i;
 }
}

echo &#39;开始前内存占用:&#39; . memory_get_usage() . PHP_EOL;
$data = generateData(100000);
echo &#39;生成完数组后内存占用:&#39; . memory_get_usage() . PHP_EOL;
unset($data);
echo &#39;释放后的内存占用:&#39; . memory_get_usage() . PHP_EOL;
Copy after login

运行得到结果:


开始前内存占用:231528
生成完数组后内存占用:231712
释放后的内存占用:231576
Copy after login

前后的差值是:184

使用yield后的效果


function generateData($max)
{
 for ($i = 0; $i <= $max; $i++) {
 yield $i;
 }
}

echo &#39;开始前内存占用:&#39; . memory_get_usage() . PHP_EOL;
$data = generateData(100000);// 这里实际上得到的是一个迭代器
echo &#39;生成完数组后内存占用:&#39; . memory_get_usage() . PHP_EOL;
unset($data);
echo &#39;释放后的内存占用:&#39; . memory_get_usage() . PHP_EOL;
Copy after login

运行结果:


开始前内存占用:228968
生成完数组后内存占用:229824
释放后的内存占用:229016
Copy after login
Copy after login

前后的差值是:856

奇怪,使用了 yield 后,内存占用反而上升了,这是什么鬼?别急。上面我们参数传入的是 1,000,00,我现在将传入参数改成改成 1,000,000试试。

第一个方法得到的结果是:


开始前内存占用:231528

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /test/yield.php on line 6
Copy after login

看了吧,一百万次的循环时,一次性载入内存,超出了限制。那么再来看 yield 的执行结果:


开始前内存占用:228968
生成完数组后内存占用:229824
释放后的内存占用:229016
Copy after login
Copy after login

前后的差值依然是:856

好了到这里,应该看出来了,yield无论数组大小,占用均是 856 ,这是因为它自身,它在你进行迭代的时候才会产生真实数据。

所以如果你的数据来源非常大,那么用 yield 吧。如果数据来源很小,当然选择一次载入内存。

总结

The above is the detailed content of In-depth understanding of static and yield keywords in php. 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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles