suin.io

Visibility keywords are changeable in PHP classes

suin2011年1月30日

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'にできない。知らんかったー。

RELATED POSTS