The visibility of a property or method can be defined by prefixing the
declaration with the keywords: public, protected or private. Public
declared items can be accessed everywhere. Protected limits access to
inherited classes (and to the class that defines the item). Private limits
visibility only to the class that defines the item.
Class members must be defined with public, private, or protected.
Example 19-8. Member declaration
<?php
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; echo $obj->protected; echo $obj->private; $obj->printHello(); class MyClass2 extends MyClass
{
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj->public; echo $obj2->private; echo $obj2->protected; $obj2->printHello(); ?>
|
|
Note:
The PHP 4 method of declaring a variable with the
var keyword is no longer valid
for PHP 5 objects. For compatibility a variable declared
in php will be assumed with public visibility, and a
E_STRICT warning will be issued.
Class methods must be defined with public, private, or protected. Methods
without any declaration are defined as public.
Example 19-9. Method Declaration
<?php
class MyClass
{
public function __construct() { }
public function MyPublic() { }
protected function MyProtected() { }
private function MyPrivate() { }
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myclass = new MyClass;
$myclass->MyPublic(); $myclass->MyProtected(); $myclass->MyPrivate(); $myclass->Foo(); class MyClass2 extends MyClass
{
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); }
}
$myclass2 = new MyClass2;
$myclass2->MyPublic(); $myclass2->Foo2(); ?>
|
|