I am creating a class with variable, as you can see from the code below, I am want to access
$allen = new guest(...); echo $allen->userName;
instead I have to use this
$allen->getUserName();
but since username won't change after the class is created, is there a way to do this?
<?php
class guest {
var $firstName;
var $lastName;
var $email;
var $userName;
function guest($firstName, $lastName, $email) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->userName = getUserName(); // option 1
$this->userName = $this->getUserName(); // option 2
preg_match('/^.*(?=(@))/i', $this->email, $userName);
$this->userName = $userName[0]; // this is messy but work
}
function getUserName() {
preg_match('/^.*(?=(@))/i', $this->email, $userName);
return $userName[0];
}
}
?>
varfor properties in a PHP class is a throwback to PHP 4, only maintained for backward compatibility..... but it is recommended that you usepublic/protected/privatevisibility instead.... however, asvaris treated aspublic,echo $allen->username;is perfectly validgetUserName()refers to$userName, not$this->userName?