note 46841 added to language.oop

From: Date: Mon, 25 Oct 2004 15:49:49 +0000
Subject: note 46841 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-79074@lists.php.net to get a copy of this message
We can't return a value with a constructor, witch would be stupid if we create an object as this : $obj = new maClasse($arg1,...); but PHP allows to use a class as a function : new maClasse($arg1,...); and if for example this class modifies a string it must return this string . We can't do a return in a constructor but we can do : class MyClass { var str; function MyClass($arg_str){ $this->str=$arg_str; $this->funct1(); //we can't do a return $this->str but we can do $this = $this->str; } function funct1(){ //... modifies $this->str } } //And now I can do : echo "This is the string :".$myStr. "<br/>This is the new string ".(new Myclass($myStr)); Sorry for my English I am french :-) En francais : Il ne faut pas oublier de préciser qu'il est normelement impossible de renvoyer une valeur avec un constructeur. Il n'y a donc pas de return dans un constructeur ce qui serait d'ailleur stupide si l'instanciation de l'objet serait faite de la facon suivant : $obj = new maClasse($arg1,...); mais en PHP il est possible (ou toléré) d'utiliser une classe comme fonction : new maClasse($arg1,...); et si cette classe (=fonction) par exemple traite une chaine de caracteres et qu'elle doit renvoyer cette chaine il est impossible de faire un return $this->chaine dans le constructeur La solution serait de placer à la fin du constructeur : $this = $this->chaine; ---- Manual Page -- http://www.php.net/manual/en/language.oop.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46841 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46841&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46841&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46841&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46841&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46841&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46841&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+46841&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#79074) next »