in this example i will show you how to use the singleton pattern in your classes so that only one instance of the object is ever created. and you can access your object anywhere without the need to use global $obj;
user.class.php
<?php
Class User {
static private $instance;
private $_name;
private $_email;
private function __construct() {
}
static function instance() {
if(!Self::$instance) {
Self::$instance = new User();
} else {
return Self::$instance
}
}
public function name($name) {
if(!$name) {
return $this->$_name;
} else {
$this->$_name = $name;
}
}
public function email($email) {
if(!$email) {
return $this->$_email;
} else {
$this->$_email = $email;
}
}
}
?>
index.php
<?php
include_once('user.class.php');
// call the user class and check to see if there is already an instance
// of the user class, if so return it otherwise create the instance.
$user = User::instance();
// set the name and email
$user->name('Joe Crawford');
$user->email('weberdev@codebowl.com');
// echo the name and email
echo $user->name();
echo '<br>';
echo $user->email();
//now say you have a class or a function that you need to gain access to the user object for, rather than doing global $user; you should do something like this.
class Something {
private $user;
public function __construct() {
$this->user = User::instance();
}
}
//this will then allow you to use $this->$user->name(); in the class.
?>
If you have any problems understanding this code feel free to comment or email me using weverdev@codebowl.com
Abdoulaye Siby wrote :1182
Hello, that`s a very useful code. However, I am wondering
how does PHP make the difference between the variable
$instance and the function instance(). Is there any reason
that they have the same spelling ? If ther is, that`s fine
but it`s really confusing for the human eye. I would have
used $var_instance instead of $instance to make the
difference clearer.
Good work ;)
Joseph Crawford wrote :1183
Actually you can use a different name, i should have used getInstance() as that is what i normally use.
sorry for the confusion
Joe Crawford Jr.
Marten van den Brand wrote :1811
I get a strange error: PHP Fatal error: Call to a member function name() on a non-object, I already added an extra piece of code to check if it's an object.
<?php
// set the name and email
if (is_object($user) ) {
die('its an object');
} else {
//die('its not an object');
}
?>
Is it something with my server? Or am I doing something wrong?