Jump to content

classes / variables


astralaaron

Recommended Posts

does anyone know where I can read about declaring variables within a class?there are a few things I am seeing that I do not understand, "public, private"i read someplace that you have to declare with the 'var' infront of the variable like in javascript...confusing information!

Link to comment
Share on other sites

Summary in response to OP's questions:You have to state the variable scope in front of a class's properties when declaring them, unless they are public (some people feel it is good practice to state public anyway).Public properties can be accessed from outside the object (see example). Private properties can only be accessed from within the object.

class Test {	public $public;	private $private;	function __construct() {		$this->public = "Public variable";		$this->private = "Private variable";	}	function show_private() {		echo $this->private;	}}$test = new Test();echo $test->public; //echos "Public variable"echo $test->private; //error$test->show_private(); //echos "Private variable"

Link to comment
Share on other sites

The reasoning behind this is more psychological than anything. Public variables are the ones you're designing the object for in the first place. Simple objects might only have public variables. More complex objects may have methods that use variables for the sake of computation only. Like a for loop iterator. What possible purpose would it serve to make its value available outside the object?But of course, you designed the object, so you know exactly which variables are useful or not. You wouldn't try to access your iterator variable outside the object because you know it would be a useless thing to do. At this level, declaring it private is more like a reminder to yourself.But then there are library classes, the kind where somebody (not you, or maybe a much younger you) designed a useful object and made it available as open source. Especially if it's big, you the "borrower" might not at first glance see what's useful, what's not, and what could actually muck things up if you played with it. Good documentation should take care of that, but here also declaring such a variable private eliminates possible problems (except for the tool-junkie who just has to look under the hood, in which case he gets what he deserves).

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...