Previous Entry в избранное рассказать другу Next Entry
Эмо-программулька
потому что мысль
[info]daochan
Решил я для забавы пощупать механизмы деструкции в PHP и в процессе оного написал такую вот штуку. Далее приведен контент, который выводится в браузер. Он содержит собственно код ("самораспечатывание") и затем результат работы смысловой части. Кирилл, надеюсь, тебе будет весело, а других френдов у меня пока ещё нет. Эй, граждане, вы куда спрятались? :)

Auto-printable source

<?php
// Cast

class CreatureException extends Exception{
       function __construct($message,Creature &$creature){
              parent::__construct($message);
              $creature->say($message);
       }
}

abstract class Creature{
       private $name,$pets,$master;
       function __construct($name){
              $this->name=$name;
              $this->pets=array();
              $this->say("Hello, world! :)");
       }
       public function getName(){
              return $this->name;
       }
       abstract protected function pronounce($blah);
       public function say($blah){
              echo"<p>{$this->name} [".get_class($this)."] said: {$this->pronounce($blah)}</p>";
       }
       public function tell(Creature &$whom, $blah){
              echo"<p>{$this->name} [".get_class($this)."] told {$whom->getName()}: {$this->pronounce($blah)}</p>";
       }
       public function tame(Creature &$pet){
              $this->tell($pet,"Hey, come here!");
              if($pet===$this) throw new CreatureException("Dammit, no one may speak to himself!",$this);
              $this->pets[]=&$pet;
              $pet->becomeAttachedTo($this);
              $this->tell($pet,"From now on you are my pet.");
       }
       public function becomeAttachedTo(Creature &$master){
              $this->master=&$master;
              $this->tell($master,"I recognize you, my master.");
       }
       public function harakiri(){
              $this->say("Harakiri!!!");
              unset($this);
              $this->say("I must be dead by now... it's a miracle!");
       }
       function __destruct(){
              foreach($this->pets as $id=>$pet){
                     if(isset($pet)){
                            $this->tell($pet,"Would you die tonight for love? Would you join me in death?");
                            $pet->harakiri();
                     }
              }
              if(isset($this->master)){
                     $this->tell($this->master,"My master, you don't exist any more, but love is a miracle again and so I can still remember your name! %)");
              }else{
                     $this->say("Without any master my life costs nothing to nobody...");
              }
              $this->say("Hasta la vista, baby! // +_+");
       }
}

class Human extends Creature{
       protected function pronounce($blah){
              return $blah;
       }
}

class Dog extends Creature{
       protected function pronounce($blah){
              return "I'm a poor speechless creature, but my eyes are kinda saying <i>&quot;{$blah}&quot;</i>";
       }
}

class Cat extends Creature{
       private static $fuckoffs=array("fuck off","screw yourself","get lost","crap!");
       protected function pronounce($blah){
              return substr($blah,0,5)."...oh, ".self::$fuckoffs[array_rand(self::$fuckoffs)]."...";
       }
}

// Source
echo"<h1>Auto-printable source</h1><div style='font:normal 12px/14px monotype;padding:10px;border:dotted 1px #aaa;'>";
echo strtr(file_get_contents(__FILE__),array(
       '&'=>'&amp;',
       '<'=>'&lt;',
       '>'=>'&gt;',
       '"'=>'&quot;',
       "\n"=>'<br/>',
       "\t"=>'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
));
echo"</div><hr/>";

// Action
echo"<h1>Creature PHP drama</h1>";
try{
       $guy=new Human("John");
       $dog=new Dog("Stinky");
       $cat=new Cat("Fluffy");

       $guy->tame($dog);
       $guy->tame($cat);
       
       $guy->tame($guy); // this may happen or may not - play with comments

       $dog->tame($cat); // despite all the PHP miracles, this never happens IRL
       
       echo"<p><b>...Success!...</b></p>";       
}
catch(CreatureException $e){
       echo "<p><b>...a bloody Exception caused the Apocalypse, the World crushes...</b></p>";
}
echo"<p><b>...if PHP was not so emo, it could be the last message, but...</b></p>";

Creature PHP drama

John [Human] said: Hello, world! :)

Stinky [Dog] said: I'm a poor speechless creature, but my eyes are kinda saying "Hello, world! :)"

Fluffy [Cat] said: Hello...oh, crap!...

John [Human] told Stinky: Hey, come here!

Stinky [Dog] told John: I'm a poor speechless creature, but my eyes are kinda saying "I recognize you, my master."

John [Human] told Stinky: From now on you are my pet.

John [Human] told Fluffy: Hey, come here!

Fluffy [Cat] told John: I rec...oh, get lost...

John [Human] told Fluffy: From now on you are my pet.

John [Human] told John: Hey, come here!

John [Human] said: Dammit, no one may speak to himself!

...a bloody Exception caused the Apocalypse, the World crushes...

...if PHP was not so emo, it could be the last message, but...

John [Human] told Stinky: Would you die tonight for love? Would you join me in death?

Stinky [Dog] said: I'm a poor speechless creature, but my eyes are kinda saying "Harakiri!!!"

Stinky [Dog] said: I'm a poor speechless creature, but my eyes are kinda saying "I must be dead by now... it's a miracle!"

John [Human] told Fluffy: Would you die tonight for love? Would you join me in death?

Fluffy [Cat] said: Harak...oh, fuck off...

Fluffy [Cat] said: I mus...oh, screw yourself...

John [Human] said: Without any master my life costs nothing to nobody...

John [Human] said: Hasta la vista, baby! // +_+

Stinky [Dog] told John: I'm a poor speechless creature, but my eyes are kinda saying "My master, you don't exist any more, but love is a miracle again and so I can still remember your name! %)"

Stinky [Dog] said: I'm a poor speechless creature, but my eyes are kinda saying "Hasta la vista, baby! // +_+"

Fluffy [Cat] told John: My ma...oh, fuck off...

Fluffy [Cat] said: Hasta...oh, fuck off...


О, на проводе Куннигсберг! *реверанс*
Записывайтесь, обещаю доставлять и дальше.)

Вот только зачем ты объекты по ссылкам передаёшь, если они по-умолчанию передаются оным образом?

Хм, а разве не клонируются? надо почитать...

public function tame(Creature &$pet){
...
$this->pets[]=&$pet;
$pet->becomeAttachedTo($this);
...
public function becomeAttachedTo(Creature &$master){
$this->master=&$master;

мне важно чтобы в этих всех ситуациях всегда была передача и присвоение по ссылке.

а когда клонируется? только и исключительно при использовании оператора clone? не верю)

о, как интересно :) вот же черти)

А, я понял, что ты имеешь ввиду. А что тебя тут по-сути смущает? Просто удалил все объекты созданные в local scope и всё как-бы. Или я не догнал чего? =)

Прикол в том, что объект вроде уже уничтожен, однако деструктор обращается к методам и свойствам как ни в чём не бывало. :)

Ммм, объект уничтожается лишь после выполнения операций в деструкторе. В свою очередь тот вполне может нормально к членам, внутри класса к которому он относится, обращаться=) Или ты о чём?

Edited at 2009-04-04 06:02 (UTC)

Не знаю как там насчёт членов, но что-то эдакое точно)


Home