A few years ago, a paragraph of the general content is that the wife called the programmer husband to say that he would buy 10 buns on the way, and if he saw a watermelon, he would buy one. As a result, the programmer husband bought a steamed stuffed bun and went home.
Recently I saw it on the internet. It's a sudden fantasy. I wrote a PHP program and restored the whole process with the program.
I. File directory structure
-/ App - Project Root Directory
-/ Buyer - Executor, here we simulate two people, a programmer, an editor, and others.
-/Coder.php
-/Editor.php
-/Boss.php - demand side (wife adults)
-/ Buy.php - Buy (or replace it with other operations)
-/ Loader.php - Automatic loading class
-/index.php - entry file
Two, code
1.index.php
<?php define('BASEDIR', __DIR__); include BASEDIR.'/App/Loader.php'; spl_autoload_register("\\App\\Loader::autoload"); //$buyer ='Coder'; // Programmer $buyer = 'Editor'; // edit $boss = new App\Boss(); $boss->callBuyer($buyer); // Call buyer $boss->getBaoZi(); // Buy some steamed buns
2.Loader.php
<?php namespace App; class Loader { public static function autoload($class) { //var_dump($class); $file = BASEDIR.'/'.str_replace('\\', '/', $class).'.php'; //echo $file; include $file; } }
3.Buy.php
<?php namespace App; class Buy { public $baoZiNum = 0; // Number of stuffed bun public $xiGuaNum = 0; // Watermelon number public $flag = true; // true: There are watermelon sellers, false: there are no watermelon sellers. public function __construct() { echo "Yes, let me do something.\n"; } public function getBaoZi() {} }
4.Boss.php
<?php namespace App; class Boss { public static $obj; public function callBuyer($user) { echo "Call $user . . . \n"; $class = "\\App\\Buyer\\".$user; $userObj = new $class; self::$obj = $userObj; } public function getBaoZi() { echo "Buy 10 steamed buns back. If you sell watermelon, buy one.\n"; self::$obj->getBaoZi(); $baoZi = self::$obj->baoZiNum; $xiGua = self::$obj->xiGuaNum; echo "I came back and bought it. $baoZi A steamed stuffed bun. $xiGua A watermelon.\n"; } }
5.Coder.php
<?php namespace App\Buyer; use App\Buy; class Coder extends Buy { public function getBaoZi() { $this->baoZiNum = 10; // Ten steamed buns to buy if($this->flag){ // There are watermelon sellers. $this->baoZiNum = 1; // Buy one } } }
6.Editor.php
<?php namespace App\Buyer; use App\Buy; class Editor extends Buy { public function getBaoZi() { $this->baoZiNum = 10; // Buy 10 steamed buns if($this->flag){ // There are watermelon sellers. $this->xiGuaNum = 1; // Buy a watermelon } } }