亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Spooky Scary PHP

Feb 25, 2025 am 09:25 AM

Spooky Scary PHP

Are you ready for pumpkin candy and cider? The annual Halloween is here again! Although the fanaticism around the world is not as good as the United States, I still want to share some "horrible" PHP tips to celebrate this festival. This post is easy and fun and will show you some of the surprising (but logical) behaviors of PHP itself, as well as those creepy (and possibly very illogical) ways some people use PHP to complete tasks. You can think of it as my holiday gift, a little bit of programmer’s “spiritual candy” – after all, why candy only kids who don’t give it all the delicacies?

Summary of key points

  • PHP may exhibit unexpected behavior, such as retaining references outside the first foreach loop, resulting in unexpected output results. This problem can be alleviated by reassigning the string using the keys of the array.
  • When using PHP to perform more complex tasks (such as shell scripts), it is crucial to understand how the execution environment is cloned when fork, and how various resources are affected in all processes. For example, when connecting to a database, it is best to connect in the parent process after the fork child process, and the child process will connect by itself if necessary.
  • Singleton pattern (actually nothing more than fancy object-oriented global variables) can make debugging difficult. It is recommended to avoid singleton mode whenever possible.
  • While unconventional coding practices like "Spooky Scary PHP" are interesting and educational, they are not usually considered good practices for writing production code, as they often involve inefficient use, unclear, or unpredictable. function or technique.

Hazed Array

Once upon a time, in a not-so-distant development studio, Arthur was still writing code late at night. He didn't know that the array he was about to use was haunted! With each tap on the keyboard, he felt a chill slipping from his spine, but he foolishly ignored this subtle premonition.

<?php
$spell = array("double", "toil", "trouble", "cauldron", "bubble");
foreach ($spell as &$word) {
    $word = ucfirst($word);
}
foreach ($spell as $word) {
    echo $word . "n";
}

Okay, this array is not really haunted, but the output is indeed unexpected:

<code>Double
Toil
Trouble
Cauldron
Cauldron</code>

The reason for this "terrifying" behavior is how PHP retains references outside the first foreach loop. When the second loop starts, $word is still a reference, pointing to the last element of the array. The first iteration of the second loop assigns "double" to $word, which overwrites the last element. The second iteration assigns "toil" to $word, overwriting the last element again. When the loop reads the value of the last element, it has been overwritten several times. To gain insight into this behavior, I recommend reading Johannes Schlüter's blog post on the topic, "References and foreach". You can also run this slightly modified version and check its output to better understand what PHP is doing:

<?php
$spell = array("double", "toil", "trouble", "cauldron", "bubble");
foreach ($spell as &$word) {
    $word = ucfirst($word);
}
foreach ($spell as $word) {
    echo $word . "n";
}

Arthur learned a very important lesson that night and fixed his code with the keys of the array to reassign the string:

<code>Double
Toil
Trouble
Cauldron
Cauldron</code>

Ghost Database Connection

PHP is increasingly being asked not only to generate web pages every day. The number of shell scripts written in PHP is increasing, and the tasks performed by these scripts are becoming more and more complex, as developers see the advantages of integrating development languages. Typically, the performance of these scripts is acceptable and the trade-offs made for convenience are proven. So Susan is writing a parallel processing task whose code is similar to the following:

<?php
$spell = array("double", "toil", "trouble", "cauldron", "bubble");
foreach ($spell as &$word) {
    $word = ucfirst($word);
}
var_dump($spell);
foreach ($spell as $word) {
    echo join(" ", $spell) . "n";
}

Her code forks the child processes to perform some long-running work in parallel, while the parent process continues to monitor the child processes and reports the results when all children terminate.

<?php
foreach ($spell as $key => $word) {
    $spell[$key] = ucfirst($word);
}

However, Susan's leadership asked her to log status information into the log instead of outputting it to standard output. Susan extended her code using a singleton pattern PDO database connection mechanism that was already included in the company's code base.

#! /usr/bin/env php
<?php
$pids = array();
foreach (range(0, 4) as $i) {
    $pid = pcntl_fork();
    if ($pid > 0) {
        echo "Fork child $pid.n";
        // record PIDs in reverse lookup array
        $pids[$pid] = true;
    } else if ($pid == 0) {
        echo "Child " . posix_getpid() . " working...n";
        sleep(5);
        exit;
    }
}
// wait for children to finish
while (count($pids)) {
    $pid = pcntl_wait($status);
    echo "Child $pid finished.n";
    unset($pids[$pid]);
}
echo "Tasks complete.n";

Susan expects to see rows in the timings table being updated; the "start time" row should list the timestamps for the entire process being started, and the "stop time" row should list the timestamps for the completion of all processes. Unfortunately, the execution throws an exception and the database does not reflect her expectations.

<code>Fork child 1634.
Fork child 1635.
Fork child 1636.
Child 1634 working...
Fork child 1637.
Child 1635 working...
Child 1636 working...
Fork child 1638.
Child 1637 working...
Child 1638 working...
Child 1637 finished.
Child 1636 finished.
Child 1638 finished.
Child 1635 finished.
Child 1634 finished.
Tasks complete.</code>
#! /usr/bin/env php
<?php
$db = Db::connection();
$db->query("UPDATE timings SET tstamp=NOW() WHERE name='start time'");

$pids = array();
foreach (range(0, 4) as $i) {
    ...
}
while (count($pids)) {
    ...
}

$db->query("UPDATE timings SET tstamp=NOW() WHERE name='stop time'");

class Db
{
    protected static $db;

    public static function connection() {
        if (!isset(self::$db)) {
            self::$db = new PDO("mysql:host=localhost;dbname=test",
                "dbuser", "dbpass");
            self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        return self::$db;
    }
}

Like Arthur's array, is Susan's database haunted? Well, if I give you the following clues, see if you can piece together this mystery: 1. When a process is fork, the parent process is copied as a child process. These replicated processes then execute in parallel from then on. 2. Static members are shared among all instances of the class.

PDO connection is wrapped as a singleton, so any reference to it in the application points to the same resource in memory. DB::connection()First return the object reference, the parent process fork, the child process continues to process, while the parent process waits, the child process terminates and PHP cleans up the resources used, and then the parent process tries to use the database object again. The connection to MySQL has been closed in the child process, so the final call fails. Naively trying to get the connection again before the final logging query won't help Susan because the same failed PDO instance will be returned because it is a singleton. I recommend avoiding singletons - they are really just fancy object-oriented global variables, which makes debugging difficult. Even in our case, the connection will still be closed by the child process, but if DB::connection() is called before the second query, it will at least return a new connection without a singleton. But a better way is to understand how the execution environment is cloned when fork, and how various resources are affected in all processes. In this case, it is best to connect to the database in the parent process after the fork child process, and the child process will connect by itself if necessary. Connections should not be shared.

<code>PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /home/susanbrown/test.php:21
Stack trace:
#0 /home/susanbrown/test.php(21): PDO->query('UPDATE timers S...')
#1 {main}</code>

Dr. Frankenstein's API

Mary Shelley's "Frankenstein" tells the story of a scientist creating life, but he feels disgusted with its ugliness and abandons it. After some unnecessary death and destruction, Dr. Frankenstein pursues his creation until the end of the world, trying to destroy it. Many of us have given such ugly code life that we later wished we could escape it—the code is so ugly, so dull, so chaotic that it makes us want to vomit, but it just wants love and understanding. A few years ago I've been playing around with an idea about database interfaces and what they would look like if they were more strictly following Unix's philosophy of "everything is a file": queries will be written to "file", result sets Will be read from the "file". One thing leads to another, after some of my own death and destructive coding, I wrote the following class that has little to do with my initial thoughts:

<?php
$spell = array("double", "toil", "trouble", "cauldron", "bubble");
foreach ($spell as &$word) {
    $word = ucfirst($word);
}
foreach ($spell as $word) {
    echo $word . "n";
}

The result is genius, but disgusting: an instance that looks like an object (no real API method), an array, or a string...

<code>Double
Toil
Trouble
Cauldron
Cauldron</code>

I wrote a blog shortly after that and marked it as evil. Friends and colleagues who saw it almost all responded the same way: "Great! Kill it now... burn it with fire." But over the years, I admit I've softened it. The only rule it really violates is the programmer's expectations for bland naming methods like query() and result(). Instead, it uses the query string itself as the query method, the object is the interface and the result set is the result. Of course, it's not worse than an overgeneralized ORM interface, which links select() and where() methods together, which looks like SQL queries, but has more ->. Maybe my class isn't that evil? Maybe it just wants to be loved? Of course I don't want to die in the Arctic!

Conclusion

I hope you enjoyed this post and that these examples don't bring you (too many) nightmares! I believe you also have your own stories about haunted or terrible code, no matter where you are, you don't need to let the holiday fun go away, so feel free to share your terrible PHP story in the comments below! Pictures from Fotolia

(The following is FAQ, which has been adjusted and streamlined according to the original content)

Frequently Asked Questions about "Spooky Scary PHP"

What is "Spooky Scary PHP"?

"Spooky Scary PHP" is a unique PHP encoding method that involves the use of unconventional or unexpected methods to achieve certain results. This may include using lesser-known functions, taking advantage of features in the language, and even using code that doesn't seem to work but does work. It's a fun and exciting way to explore the depth of PHP and often lead to surprising and inspiring discoveries.

How to start learning "Spooky Scary PHP"?

The best way to learn "Spooky Scary PHP" is to have a solid understanding of the basics of PHP. Once you’re happy with the basics, you can start exploring the more obscure corners of the language. Reading articles, tutorials, and forum discussions about "Spooky Scary PHP" can also be very helpful. Remember, the goal is not to write efficient or practical code, but to explore and understand the language in a deeper way.

Is "Spooky Scary PHP" a good practice?

"Spooky Scary PHP" is not usually considered a good practice for writing production code. It usually involves the use of inefficient, unclear, or unpredictable functions or techniques. However, it may be a great way to learn more about the language and to challenge your understanding of PHP. It's more like a learning tool and fun experiment than a practical coding style.

Is "Spooky Scary PHP" harmful?

While "Spooky Scary PHP" is fun and educational, be sure to use it responsibly. Some technologies used in "Spooky Scary PHP" can cause harm if used in real-time environments, such as those that exploit features or errors in the language. Be sure to thoroughly test any code you write and never use the "Spooky Scary PHP" technology in important parts of your project.

The above is the detailed content of Spooky Scary 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles