Winnipeg Photographer


Example of STATIC Properties in PHP

PHP STATIC property example

Back to OOP Chapter 2

class users
{
	//properties go here
	protected $_thisUser;
	protected $_userName;
	protected $_firstName;
	protected $_lastName;
	protected $_phoneNumber;
	protected static $userNumber = 0;

	//methods go here
	public function __construct($userName,$firstName,$lastName,$phoneNumber)
	{
		$this->_userName = $userName;
		$this->_firstName = $firstName;
		$this->_lastName = $lastName;
		$this->_phoneNumber = $phoneNumber;
		self::$userNumber++;
	}//end of construct

	public function outputUserInfo()
	{
		echo $this->_userName . "\n";
		echo 'First Name: ' . $this->_firstName . "\n";
		echo 'Last Name: ' . $this->_lastName . "\n";
		echo 'Phone #: ' . $this->_phoneNumber . "\n";
		echo 'User #: ' . self::$userNumber . "\n";
		echo "\n\n\n";
	}//end of outputUserInfo

}//End of users class

$users = new users('jheinrichs','Jared','Heinrichs',222-2222');
$users->outputUserInfo();
$users = new users('dheinrichs','Delila','Heinrichs','222-2223');
$users->outputUserInfo();
$users = new users('rheinrichs','Rochelle','Heinrichs','222-2224');
$users->outputUserInfo();

Output Would look like:

jheinrichs
First Name: Jared
Last Name: Heinrichs
Phone #: 415-4085
User #: 1

dheinrichs
First Name: Delila
Last Name: Heinrichs
Phone #: 415-4085
User #: 2

rheinrichs
First Name: Rochelle
Last Name: Heinrichs
Phone #: 477-0956
User #: 3

How would it look without a STATIC Property?

jheinrichs
First Name: Jared
Last Name: Heinrichs
Phone #: 415-4085
User #: 1

dheinrichs
First Name: Delila
Last Name: Heinrichs
Phone #: 415-4085
User #: 1

rheinrichs
First Name: Rochelle
Last Name: Heinrichs
Phone #: 477-0956
User #: 1

Why does it work this way

As you see the user number does NOT increment they way it you might think it should. Every time we created a new “OBJECT” the user number became “0″. In the constructor function it was then incremented to “1″. Going back to when the Property was STATIC the “User number belonged to the WHOLE object. So when we created the 2nd and 3rd users the last value was available.


Leave a Reply