にゃあ

Visibility keywords are changeable in PHP classes

Today, I found out that some properties or methods visibility can be changed with class-extending. That fact is unexpected for me. Because, I have believed that "access levels cannot changed in child classes."

Test Code

Look at this example. I prepared two classes for testing. The file name is test.php.

test.php
<?php
class Object
{
	public $myPublic = 'public';
	protected $myProtected = 'protected';

	public function myPublic()
	{
	}

	protected function myProtected()
	{
	}
}

class ChildObject extends Object
{
	protected $myPublic = 'public'; // ...(A)
	public $myProtected = 'protected'; // ...(B)

	protected function myPublic() // ...(A')
	{
	}

	public function myProtected() // ...(B')
	{
	}
}

Object class is a super-class for ChildObject. It has two protected members and two public members.

Also, ChildObject has two protected members and two public members. However, the access level keywords are changed. public was changed to protected, and protected was changed to public.

Test Result

I executed test.php. Then, two error occurred. The first error was for (A). The second one was for (A'). This means that errors occurred only in members which are defined as public access level in the super-class. In contrast, other members which are defined as protected access level in the super-class have no errors.

  • For (A): PHP Fatal error: Access level to ChildObject::$myPublic must be public (as in class Object)
  • For (A'): PHP Fatal error: Access level to ChildObject::myPublic() must be public (as in class Object)

Conclusion

From this result, I made a conclusion. 'protected' access level properties or methods in a parent class can be changed to 'public' in child classes. 'public' access level properties or methods in a parent class CANNOT be changed to 'protected' in child classes.

Japanese:

上位クラスで'protected'なものは、下位クラスで'public'にできる。上位クラスで'public'なのは、下位クラスで'protected'にできない。知らんかったー。


コメント&トラバ

トラックバックを送る

無関係なスパムのトラックバックを防止するため、リンク先で本サイト(suin.asia)への言及が確認されないトラックバックは破棄しています。

トラバURL : http://suin.asia/trackback/490

コメントを書く

お名前* URL
本文*
合い言葉* ←「boheal9」と入力して下さい。
* この記事の話題と関係ないコメントはどんな内容でも削除します。(移動できないので)

トラックバック

トラックバックがないのはさみしいにゃん…。

コメント

コメントはないです。誰かコメント書いてよぅ…。

Author

Submenu

Recent Entries

XOOPS Cube Dev Ring

氷川 XOOPS Module 開発室

Recent Comments

Recent Trackbacks