Visibility in PHP

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 and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.

A note about private members, the doc says “Private limits visibility only to the class that defines the item” this says that the following code works as espected:

class A {
private $_myPrivate="private";

public function showPrivate()
{
echo $this->_myPrivate.”n”;
}
}

class B extends A {
public function show()
{
$this->showPrivate();
}
}

$obj=new B();
$obj->show(); // shows “privaten”;
?>

this works cause A::showPrivate() is defined in the same class as $_myPrivate and has access to it.

You may define grouped variables separated by commas if they have the same visibility. This works for both initialized and uninitialized variables.

class Window
{
public $x = 0, $y = 100, $width = 1024, $height = 768;
}
?>

Handy if no comments are required or you’re inside a DocBlock.

此条目发表在 Programming 分类目录,贴了 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">