search
HomeBackend DevelopmentPHP TutorialUse static to avoid 'repeated reading'_PHP tutorial

Use static to avoid 'repeated reading'_PHP tutorial

Jul 21, 2016 pm 02:55 PM
staticwebuseexistcomplexobjectoperatedataofProgram developmentavoiduseFor

In the development of more complex web programs, due to the object-oriented data operation method or the business logic is too complex, developers often unconsciously read data repeatedly during the development process.
For example:
$result1 = tableobjectPeer::getResult($var1,$var2,$var3);
When developers need the table data, they often call the tableobjectPeer::getResult method directly.
Or when the program is forwarding, it will also cause repeated calls to the tableobjectPeer::getResult method, resulting in "repeated reading".

To avoid similar "repeated reading", the most important way is for developers to have the awareness of "avoiding repeated reading" when developing code.
In fact, just do it where needed after:
$result1 = tableobjectPeer::getResult($var1,$var2,$var3);

$result2 = $result1;
$ result3 = $result1;
is enough. In this way, a large number of "repeated reads" can be avoided.
But if the developers didn't do this at the beginning, it may be a lot of work to refactor in this area.
In addition, due to the forward() in the framework, it is easy to cause "repeated reading". If "repeated reading" is caused by forward(), then this method is not feasible (this may be related to different development languages ​​and different development frameworks, as is the case in PHP's symfony framework).

Therefore, while using the above method for optimization, for some more complex situations, we decided to use another method: Use static and set the variable to a static variable to avoid repeated reading of data. .

The following is the quoted content:
以下为引用的内容:
//要改写的函数也请加上$is_static=1变量,用来控制是否开启 static。
function staticFunc ($var1,$var2,$var3,$is_static=1)
{
if ( $is_static == 1 )//默认需要缓存函数结果
{
static $result_array;//该数组用来保存函数的结果,支持不同参数的结果缓存
$vars_string = serialize( func_get_args() );

if ( empty( $result_array ) )//第一次运行需要初始化
{
$result_array = array();
}

if ( array_key_exists( $vars_string, $result_array ) )//参数已经存在
{
return $result_array[$vars_string];//返回静态变量中已经保存的结果
}else//参数不存在
{
$result_array[$vars_string] = '';//后面会把结果补充进来
}
}else//不利用static 缓冲结果
{
if ( empty( $result_array ) )
{
$result_array = array();
}
}

$result_array[$vars_string] = rand();//获取结果,请把获取的代码放在此处即可
return $result_array[$vars_string];
}

echo staticFunc(1,2,3);
echo "
";
echo staticFunc(2,2,2);
echo "
";
echo staticFunc(1,2,3);
echo "
";
echo staticFunc(2,2,2);
echo "
";
echo staticFunc(3,3,3);
echo "
";
echo staticFunc(3,3,3,0);
echo "
";
?>
/ / Please also add the $is_static=1 variable to the function to be rewritten to control whether static is turned on. function staticFunc ($var1,$var2,$var3,$is_static=1) { if ( $is_static == 1 )//The function result needs to be cached by default { static $result_array;//This array is used to save the results of the function and supports result caching of different parameters$vars_string = serialize( func_get_args() ); if ( empty( $result_array ) )//Chapter One run requires initialization { $result_array = array(); } if ( array_key_exists( $vars_string, $result_array ) )//The parameters already exist { return $result_array[$vars_string];//Return the result saved in the static variable}else//The parameter does not exist{ $result_array[$vars_string] = '';//After The results will be added } }else//Do not use static buffering results { if ( empty( $result_array ) ) { $result_array = array(); } } $result_array[$vars_string] = rand();//To get the result, please put the obtained code herereturn $result_array[$vars_string ]; } echo staticFunc(1,2,3); echo "
"; echo staticFunc(2,2,2); echo "
"; echo staticFunc(1,2,3); echo "
"; echo staticFunc(2,2,2); echo "< ;br>"; echo staticFunc(3,3,3); echo "
"; echo staticFunc(3,3,3,0); echo "< ;br>"; ?>

Running the above code produces results similar to:
16667
8888
16667
8888
2193
1014
It can be seen that the results of lines 1 and 3 are consistent, and the results of lines 2 and 4 are consistent, indicating that as long as the parameters of the function are the same, the function results are effectively "cache".
From lines 4 and 5, it can be seen that setting the $is_static variable can effectively control whether to enable "cache".

Supplement: Using the static method above can effectively avoid reading data repeatedly in one thread, but the cache only exists in one thread, and different threads are independent of each other. Although it is just the "cache" of the function result within the thread, its principle is similar to other methods of cache, that is, the cache key must be constructed for different parameters (different situations).

Reprinted from: http://www.cnblogs.com/rethink/

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364345.htmlTechArticleIn the development of more complex web programs, due to the use of object-oriented data operation methods, or the business logic is too complex , developers often read repeatedly unconsciously during the development process...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 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.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment