note 11540 added to Classes and Objects
| From: | idont at remember dot it | Date: | Fri, 23 Feb 2001 18:47:59 +0000 |
| Subject: | note 11540 added to Classes and Objects | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-11488@lists.php.net to get a copy of this message | ||
In many exemples (and in the official doc) I saw a problem: many access directly the attributs of
the objects. Actually we SHOULD always access an attribut through a method.
<?php
class user{
var $_name;
var $_email;
function user($name,$email){
$this->_name=$name;
$this->_email=$email;
}
function getName(){
return($this->_name);
}
function getEmail(){
return($this->_email);
}
function setName($name){
$this->_name=$name;
}
function setEmail($email){
$this->_email=$email;
}
}
$me = new user("Bill","billclinton@whitehouse.org");
echo "my name is :".$me->getName()."<br>";
echo "and my email :".$me->getEmail()."<br>";
//wrong way
$me->_email="billclinton@retired.com";
//Better way
$me->setEmail("billclinton@retired.com");
//wrong way
echo "oops sorry, here is the right one:".$me->_email."<br>";
//Better way
echo "oops sorry, here is the right one:".$me->getEmail()."<br>";
?>
As you noticed I put a "_" at the beginning of the attributs' names, this is a typo
tip to declare them as private. OF course this is not real as PHP doesn't support the notions
of public, private for methods and attributs.
A poor solution waiting for a better one. :)
http://www.php.net/manual/en/language.oop.php