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();
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 '开始前内存占用:' . memory_get_usage() . PHP_EOL; $data = generateData(100000); echo '生成完数组后内存占用:' . memory_get_usage() . PHP_EOL; unset($data); echo '释放后的内存占用:' . memory_get_usage() . PHP_EOL;
运行得到结果:
开始前内存占用:231528 生成完数组后内存占用:231712 释放后的内存占用:231576
前后的差值是:184
使用yield后的效果
function generateData($max) { for ($i = 0; $i <= $max; $i++) { yield $i; } } echo '开始前内存占用:' . memory_get_usage() . PHP_EOL; $data = generateData(100000);// 这里实际上得到的是一个迭代器 echo '生成完数组后内存占用:' . memory_get_usage() . PHP_EOL; unset($data); echo '释放后的内存占用:' . memory_get_usage() . PHP_EOL;
运行结果:
开始前内存占用:228968 生成完数组后内存占用:229824 释放后的内存占用:229016
前后的差值是: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
看了吧,一百万次的循环时,一次性载入内存,超出了限制。那么再来看 yield 的执行结果:
开始前内存占用:228968 生成完数组后内存占用:229824 释放后的内存占用:229016
前后的差值依然是: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!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

在php中,可以利用ltrim()函数来去掉字符串首位的tab空白符,语法为“ltrim(string)”;当只给ltrim()函数传入一个参数,用于规定要检查的字符串时,可删除该字符串开始位置的空白字符(例空格、tab制表符、换行符等)。


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 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment