Public data members break one of the key OO concepts, namely 'encapsulation'. Encapsulation means that an 'instance' (i.e. an object) of a class controls its internal data, and only allows access to it through member functions. You can have a getFoo() function that returns some data (by value, or as a copy), and a setFoo() function that allows others to modify data in a controlled way. For instance, if the data is a numeric value that must not be negative, the setFoo() member function could reject any value below zero.
Example class:
PHP Code:
class Foo
{
public $a;
private $b;
}
var $myFoo = new Foo;
$myFoo->a = 13; // Allowed.
$myFoo->b = 69; // Not allowed! $myFoo->b is private.
The constructor is called when you create an instance of a class. Its name is the same as the class name. Example:
PHP Code:
class Bar
{
public $x;
function Bar()
{
$this->x = 1;
}
}
var $myBar = new Bar;
echo $myBar->x; // Writes '1'.
Note that you don't explicitly call $myBar->Bar(). It's called automatically when you do 'new Bar'.
Bookmarks