Thursday, May 12, 2011

Visibility

more info.. http://evergreenphp.blogspot.com

Visibility
The visibility of a property or method can be defined by prefixing the declaration with the keywords
public, protectedor private. Class members declared public can be accessed everywhere. Members
declared protected can be accessed only within the class itself and by inherited and parent classes.
Members declared as private may only be accessed by the class that defines the member.
Property Visibility
Class properties must be defined as public, private, or protected. If declared usingvar without an
explicit visibility keyword, the property will be defined as public.
Note: The PHP 4 method of declaring a variable with thevar keyword is still supported for
compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its
usage would generate anE_STRICT warning.
public;
echo$this->protected;
echo$this->private;
}
}$obj = new MyClass();
echo$obj->public; // Works
echo$obj->protected; // Fatal Error
echo$obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
/**
* Define MyClass2
*/
classMyClass2 extendsMyClass
{
// We can redeclare the public and protected method, but not
private
protected$protected ='Protected2';
functionprintHello()
{
echo$this->public;
echo$this->protected;
echo$this->private;
}
}$obj2 = new MyClass2();
echo$obj2->public; // Works
echo$obj2->private; // Undefined
echo$obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>

Method Visibility
Class methods may be defined as public, private, or protected. Methods declared without any
explicit visibility keyword are defined as public.
MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
/**
* Define MyClass2
*/
classMyClass2 extendsMyClass
{
// This is public
functionFoo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
classBar
{
public functiontest() {
$this->testPrivate();
$this->testPublic();
}public functiontestPublic() {
echo"Bar::testPublic\n";
}private functiontestPrivate() {
echo"Bar::testPrivate\n";
}
}classFoo extendsBar
{
public functiontestPublic() {
echo"Foo::testPublic\n";
}private functiontestPrivate() {
echo"Foo::testPrivate\n";
}
}$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>

No comments: