Classes and Initializing Variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Classes and Initializing Variables

Post by Sindarin »

Is it generally good practice to do:

Code: Select all

class MyClass{

	public $testvar;
	
	public function __construct(){
		$this->testvar = 1;
	}

}
instead of:

Code: Select all

class MyClass{

	public function __construct(){
		$this->testvar = 1;
	}

}
or is it redundant?
maxx99
Forum Contributor
Posts: 142
Joined: Mon Nov 21, 2011 3:40 am

Re: Classes and Initializing Variables

Post by maxx99 »

In second case $testvar is just undeclared. In PHP you don't have to declare your class variables, but its a good practice:
- you have a clear list of your variables
- you can set visibility (public/private)
- you can add PHPDOC description of this variable
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Classes and Initializing Variables

Post by social_experiment »

http://framework.zend.com/manual/en/cod ... style.html
Look at the 'classes' section of this page for more information
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply