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
foreach
loop, resulting in unexpected output results. This problem can be alleviated by reassigning the string using the keys of the array. 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!