略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 访问控制(可见性)

2024-12-23

访问控制(可见性)

对属性或方法的访问控制(PHP 7.1.0 以后支持常量),是通过在前面添加关键字 public(公有),protected(受保护)或 private(私有)来实现的。被定义为公有的类成员可以在任何地方被访问。 被定义为受保护的类成员则可以被其自身以及其子类和父类访问。被定义为私有的类成员则只能被其定义所在的类访问。

属性的访问控制

类属性可以定义为public, private 或者 protected。在没有任何访问控制关键字的情况下,属性声明为 public。

示例 #1 属性声明

<?php
/**
 * Define MyClass
 */
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(); // 输出 Public、Protected 和 Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// 可以对 public 和 protected 进行重定义,但 private 而不能
    
public $public 'Public2';
    protected 
$protected 'Protected2';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj2 = new MyClass2();
echo 
$obj2->public// 这行能被正常执行
echo $obj2->protected// 这行会产生一个致命错误
echo $obj2->private// 未定义 private
$obj2->printHello(); // 输出 Public2、Protected2 和 Undefined

?>

方法的访问控制

类中的方法可以被定义为公有,私有或受保护。如果没有设置这些关键字,则该方法默认为公有。

示例 #2 方法声明

<?php
/**
 * Define MyClass
 */
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(); // 公有,受保护,私有都可以执行


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// 此方法为公有
    
function Foo2()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate(); // 这行会产生一个致命错误
    
}
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // 这行能被正常执行
$myclass2->Foo2(); // 公有的和受保护的都可执行,但私有的不行

class Bar 
{
    public function 
test() {
        
$this->testPrivate();
        
$this->testPublic();
    }

    public function 
testPublic() {
        echo 
"Bar::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Bar::testPrivate\n";
    }
}

class 
Foo extends Bar 
{
    public function 
testPublic() {
        echo 
"Foo::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate 
                // Foo::testPublic
?>

常量的控制访问

PHP 7.1.0 开始,类的常量可以定义为公有、私有或受保护。如果没有设置这些关键字,则该常量默认为公有。

示例 #3 PHP 7.1.0 中的常量声明

<?php
/**
 * Define MyClass
 */
class MyClass
{
    
// 公有常量
    
public const MY_PUBLIC 'public';

    
// 受保护的常量
    
protected const MY_PROTECTED 'protected';

    
// 私有常量
    
private const MY_PRIVATE 'private';

    public function 
foo()
    {
        echo 
self::MY_PUBLIC;
        echo 
self::MY_PROTECTED;
        echo 
self::MY_PRIVATE;
    }
}

$myclass = new MyClass();
MyClass::MY_PUBLIC// 这行可以正常执行
MyClass::MY_PROTECTED// 这行会产生一个致命错误 
MyClass::MY_PRIVATE// 这行会产生一个致命错误
$myclass->foo(); // 将会输出:Public Protected Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass
{
    
// This is public
    
function foo2()
    {
        echo 
self::MY_PUBLIC;
        echo 
self::MY_PROTECTED;
        echo 
self::MY_PRIVATE// 这行会产生一个致命错误
    
}
}

$myclass2 = new MyClass2;
echo 
MyClass2::MY_PUBLIC// 这行可以正常执行
$myclass2->foo2(); // 将会输出:Public Protected,MY_PRIVATE 是私有常量,无法输出
?>

其它对象的访问控制

同一个类的对象即使不是同一个实例也可以互相访问对方的私有与受保护成员。 这是由于在这些对象的内部具体实现的细节都是已知的。

示例 #4 访问同一个对象类型的私有成员

<?php
class Test
{
    private 
$foo;

    public function 
__construct($foo)
    {
        
$this->foo $foo;
    }

    private function 
bar()
    {
        echo 
'Accessed the private method.';
    }

    public function 
baz(Test $other)
    {
        
// 我们可以改变私有属性:
        
$other->foo 'hello';
        
var_dump($other->foo);

        
// 我们也可以调用私有方法:
        
$other->bar();
    }
}

$test = new Test('test');

$test->baz(new Test('other'));
?>

以上例程会输出:

string(5) "hello"
Accessed the private method.
add a noteadd a note

User Contributed Notes 27 notes

up
281
wbcarts at juno dot com
10 years ago
INSIDE CODE and OUTSIDE CODE

<?php

class Item
{
 
/**
   * This is INSIDE CODE because it is written INSIDE the class.
   */
 
public $label;
  public
$price;
}

/**
* This is OUTSIDE CODE because it is written OUTSIDE the class.
*/
$item = new Item();
$item->label = 'Ink-Jet Tatoo Gun';
$item->price = 49.99;

?>

Ok, that's simple enough... I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:
* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it -- huge mistake.
* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) -- another huge mistake.

Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that's it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.

INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float -- which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.

<?php

class Item
{
 
/**
   * Here's the new INSIDE CODE and the Rules to follow:
   *
   * 1. STOP ACCESS to properties via $item->label and $item->price,
   *    by using the protected keyword.
   * 2. FORCE the use of public functions.
   * 3. ONLY strings are allowed IN & OUT of this class for $label
   *    via the getLabel and setLabel functions.
   * 4. ONLY floats are allowed IN & OUT of this class for $price
   *    via the getPrice and setPrice functions.
   */

 
protected $label = 'Unknown Item'; // Rule 1 - protected.
 
protected $price = 0.0;            // Rule 1 - protected.

 
public function getLabel() {       // Rule 2 - public function.
   
return $this->label;             // Rule 3 - string OUT for $label.
 
}

  public function
getPrice() {       // Rule 2 - public function.   
   
return $this->price;             // Rule 4 - float OUT for $price.
 
}

  public function
setLabel($label)   // Rule 2 - public function.
 
{
   
/**
     * Make sure $label is a PHP string that can be used in a SORTING
     * alogorithm, NOT a boolean, number, array, or object that can't
     * properly sort -- AND to make sure that the getLabel() function
     * ALWAYS returns a genuine PHP string.
     *
     * Using a RegExp would improve this function, however, the main
     * point is the one made above.
     */

   
if(is_string($label))
    {
     
$this->label = (string)$label; // Rule 3 - string IN for $label.
   
}
  }

  public function
setPrice($price)   // Rule 2 - public function.
 
{
   
/**
     * Make sure $price is a PHP float so that it can be used in a
     * NUMERICAL CALCULATION. Do not accept boolean, string, array or
     * some other object that can't be included in a simple calculation.
     * This will ensure that the getPrice() function ALWAYS returns an
     * authentic, genuine, full-flavored PHP number and nothing but.
     *
     * Checking for positive values may improve this function,
     * however, the main point is the one made above.
     */

   
if(is_numeric($price))
    {
     
$this->price = (float)$price; // Rule 4 - float IN for $price.
   
}
  }
}

?>

Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you... which means you can keep your hair!
up
122
what at ever dot com
13 years ago
If you have problems with overriding private methods in extended classes, read this:)

The manual says that "Private limits visibility only to the class that defines the item". That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the "same" private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them. Scopes are different. In other words -- each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

<?php
abstract class base {
    public function
inherited() {
       
$this->overridden();
    }
    private function
overridden() {
        echo
'base';
    }
}

class
child extends base {
    private function
overridden() {
        echo
'child';
    }
}

$test = new child();
$test->inherited();
?>

Output will be "base".

If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That's what it is for:)

A sample that works as intended:

<?php
abstract class base {
    public function
inherited() {
       
$this->overridden();
    }
    protected function
overridden() {
        echo
'base';
    }
}

class
child extends base {
    protected function
overridden() {
        echo
'child';
    }
}

$test = new child();
$test->inherited();
?>
Output will be "child".
up
58
pgl at yoyo dot org
6 years ago
Just a quick note that it's possible to declare visibility for multiple properties at the same time, by separating them by commas.

eg:

<?php
class a
{
    protected
$a, $b;

    public
$c, $d;

    private
$e, $f;
}
?>
up
31
stephane at harobed dot org
15 years ago
A class A static public function can access to class A private function :

<?php
class A {
    private function
foo()
    {
        print(
"bar");
    }

    static public function
bar($a)
    {
       
$a->foo();
    }
}

$a = new A();

A::bar($a);
?>

It's working.
up
15
r dot wilczek at web-appz dot de
16 years ago
Beware: Visibility works on a per-class-base and does not prevent instances of the same class accessing each others properties!

<?php
class Foo
{
    private
$bar;

    public function
debugBar(Foo $object)
    {
       
// this does NOT violate visibility although $bar is private
       
echo $object->bar, "\n";
    }

    public function
setBar($value)
    {
       
// Neccessary method, for $bar is invisible outside the class
       
$this->bar = $value;
    }
   
    public function
setForeignBar(Foo $object, $value)
    {
       
// this does NOT violate visibility!
       
$object->bar = $value;
    }
}

$a = new Foo();
$b = new Foo();
$a->setBar(1);
$b->setBar(2);
$a->debugBar($b);        // 2
$b->debugBar($a);        // 1
$a->setForeignBar($b, 3);
$b->setForeignBar($a, 4);
$a->debugBar($b);        // 3
$b->debugBar($a);        // 4
?>
up
10
alexaulbach at mayflower dot de
9 years ago
<?php

error_reporting
(E_ALL | E_STRICT E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);

class
A
{
        private
$private = 1;
        public
$public = 1;

        function
get()
        {
                return
"A: $this->private , $this->public\n";
        }

}

class
B extends A
{

        function
__construct()
        {
               
$this->private = 2;
               
$this->public = 2;
        }

        function
set()
        {
               
$this->private = 3;
               
$this->public = 3;
        }

        function
get()
        {
                return
parent::get() . "B: $this->private , $this->public\n";
        }

}

$B = new B;

echo
$B->get();
echo
$B->set();
echo
$B->get();
?>

?>

Result is
A: 1 , 2
B: 2 , 2
A: 1 , 3
B: 3 , 3

This is correct code and does not warn you to use any private.

"$this->private" is only in A private. If you write it in class B it's a runtime declaration of the public variable "$this->private", and PHP doesn't even warn you that you create a variable in a class without declaration, because this is normal behavior.
up
13
Marce!
12 years ago
Please note that protected methods are also available from sibling classes as long as the method is declared in the common parent. This may also be an abstract method.

In the below example Bar knows about the existence of _test() in Foo because they inherited this method from the same parent. It does not matter that it was abstract in the parent.

<?php
abstract class Base {
    abstract protected function
_test();
}

class
Bar extends Base {
   
    protected function
_test() { }
   
    public function
TestFoo() {
       
$c = new Foo();
       
$c->_test();
    }
}

class
Foo extends Base {
    protected function
_test() {
        echo
'Foo';
    }
}

$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>
up
7
imran at phptrack dot com
12 years ago
Some Method Overriding rules :

1. In the overriding, the method names and arguments (arg’s) must be same.

Example:
class p { public function getName(){} }
class c extends P{ public function getName(){} }

2. final methods can’t be overridden.

3. private methods never participate in the in the overriding because these methods are not visible in the child classes.

Example:
class a {
private  function my(){   
    print "parent:my";
}
public function getmy(){
$this->my();
}
}
class b extends a{
    private  function my(){
        print "base:my";       
}
}
$x = new b();
$x->getmy(); // parent:my

4. While overriding decreasing access specifier is not allowed

class a {
public  function my(){   
    print "parent:my";
}

}
class b extends a{
    private  function my(){
        print "base:my";       
}
}
//Fatal error:  Access level to b::my() must be public (as in class a)
up
10
omega at 2093 dot es
9 years ago
This has already been noted here, but there was no clear example. Methods defined in a parent class can NOT access private methods defined in a class which inherits from them. They can access protected, though.

Example:

<?php

class ParentClass {

    public function
execute($method) {
       
$this->$method();
    }
   
}

class
ChildClass extends ParentClass {

    private function
privateMethod() {
        echo
"hi, i'm private";
    }
   
    protected function
protectedMethod() {
        echo
"hi, i'm protected";
    }
   
}

$object = new ChildClass();

$object->execute('protectedMethod');

$object->execute('privateMethod');

?>

Output:

hi, i'm protected
Fatal error: Call to private method ChildClass::privateMethod() from context 'ParentClass' in index.php on line 6

In an early approach this may seem unwanted behaviour but it actually makes sense. Private can only be accessed by the class which defines, neither parent nor children classes.
up
8
IgelHaut
10 years ago
<?php
class test {
    public
$public = 'Public var';
    protected
$protected = 'protected var';
    private
$private = 'Private var';
   
    public static
$static_public = 'Public static var';
    protected static
$static_protected = 'protected static var';
    private static
$static_private = 'Private static var';
}

$class = new test;
print_r($class);
?>

The code prints
test Object ( [public] => Public var [protected:protected] => protected var [private:test:private] => Private var )

Functions like print_r(), var_dump() and var_export() prints public, protected and private variables, but not the static variables.
up
6
jc dot flash at gmail dot com
10 years ago
if not overwritten, self::$foo in a subclass actually refers to parent's self::$foo
<?php
class one
{
    protected static
$foo = "bar";
    public function
change_foo($value)
    {
       
self::$foo = $value;
    }
}

class
two extends one
{
    public function
tell_me()
    {
        echo
self::$foo;
    }
}
$first = new one;
$second = new two;

$second->tell_me(); // bar
$first->change_foo("restaurant");
$second->tell_me(); // restaurant
?>
up
2
tushar dot khan0122 at gmail dot com
3 years ago
1 . If the class member declared as public then it can be accessed everywhere.
2 . If the class members declared as protected then it can be accessed only within the class itself and by inheriting and parent classes.
3 .If the class members declared as private then it may only be accessed by the class that defines the member.

<?php
 
// BaseClass
class pub {
    public
$tag_line = "A Computer Science Portal for Geeks!";
    function
display() {
        echo
$this->tag_line."<br/>";
    }
}
 
// SubClass
class child extends pub {
    function
show(){
        echo
$this->tag_line;
    }

 
// Object Declaration
$obj= new child;
 
// A Computer Science Portal for Geeks!
echo $obj->tag_line."<br/>"
 
// A Computer Science Portal for Geeks!
$obj->display(); 
 
// A Computer Science Portal for Geeks!
$obj->show(); 
?>

<?php
 
// Base Class
class pro {
    protected
$x = 500;
    protected
$y = 500;
             
   
// Subtraction Function
   
function sub() 
    {
        echo
$sum=$this->x-$this->y . "<br/>";
    }     

 
// SubClass - Inherited Class
class child extends pro {
    function
mul() //Multiply Function
   
{
        echo
$sub=$this->x*$this->y;
    }

 
$obj= new child;
$obj->sub();
$obj->mul();
?>

<?php
 
// Base Class
class demo {
    private
$name="A Computer Science Portal for Geeks!";
     
    private function
show()
    {
        echo
"This is private method of base class";
    }

 
// Sub Class
class child extends demo {
    function
display()
    {
        echo
$this->name;
    }

 
// Object Declaration
$obj= new child;
 
// Uncaught Error: Call to private method demo::show()
$obj->show(); 
 
//Undefined property: child::$name
$obj->display(); 
?>
up
2
bishop at php dot net
5 years ago
> Members declared protected can be accessed only within
> the class itself and by inherited classes. Members declared
> as private may only be accessed by the class that defines
> the member.

This is not strictly true. Code outside the object can get and set private and protected members:

<?php
class Sealed { private $value = 'foo'; }

$sealed = new Sealed;
var_dump($sealed); // private $value => string(3) "foo"

call_user_func(\Closure::bind(
    function () use (
$sealed) { $sealed->value = 'BAZ'; },
   
null,
   
$sealed
));

var_dump($sealed); // private $value => string(3) "BAZ"

?>

The magic lay in \Closure::bind, which allows an anonymous function to bind to a particular class scope. The documentation on \Closure::bind says:

> If an object is given, the type of the object will be used
> instead. This determines the visibility of protected and
> private methods of the bound object.

So, effectively, we're adding a run-time setter to $sealed, then calling that setter. This can be elaborated to generic functions that can force set and force get object members:

<?php
function force_set($object, $property, $value) {
   
call_user_func(\Closure::bind(
        function () use (
$object, $property, $value) {
           
$object->{$property} = $value;
        },
       
null,
       
$object
   
));
}

function
force_get($object, $property) {
    return
call_user_func(\Closure::bind(
        function () use (
$object, $property) {
            return
$object->{$property};
        },
       
null,
       
$object
   
));
}

force_set($sealed, 'value', 'quux');
var_dump(force_get($sealed, 'value')); // 'quux'

?>

You should probably not rely on this ability for production quality code, but having this ability for debugging and testing is handy.
up
3
Joshua Watt
15 years ago
I couldn't find this documented anywhere, but you can access protected and private member varaibles in different instance of the same class, just as you would expect

i.e.

<?php
class A
{
    protected
$prot;
    private
$priv;
   
    public function
__construct($a, $b)
    {
       
$this->prot = $a;
       
$this->priv = $b;
    }
   
    public function
print_other(A $other)
    {
        echo
$other->prot;
        echo
$other->priv;
    }
}

class
B extends A
{
}

$a = new A("a_protected", "a_private");
$other_a = new A("other_a_protected", "other_a_private");

$b = new B("b_protected", "ba_private");

$other_a->print_other($a); //echoes a_protected and a_private
$other_a->print_other($b); //echoes b_protected and ba_private

$b->print_other($a); //echoes a_protected and a_private
?>
up
0
kostya at eltexsoft dot com
9 months ago
I see we can redeclare private properties into child class
<?php  
class A{
        private
int $private_prop = 4;
        protected
int $protected_prop = 8;
    }

    class
B extends A{
        private
int $private_prop = 7; // we can redeclare private property!!!
       
public function printAll() {
            echo
$this->private_prop;
            echo
$this->protected_prop;
    }
    }

   
$b = new B;
   
$b->printAll(); // show 78
}
?>
up
0
Vytautas
2 years ago
I have simplified the last method (Example #4) showing how to call private function outside the class. I think this is an idea of that example:

<?php
class Test
{
    private
$foo;

    private function
bar()
    {
        echo
'Accessed the private method.';
    }

    public function
baz()
    {
       
// Calling the private method:
       
$this->bar();
    }
}
$test=new Test();
$test->baz();
$test->bar();
?>
up
-8
andrei at leapingbytes dot net
9 years ago
Interestingly enough, PHP does very reasonable job in regards to interaction between classes and plain functions (even ones defined in the same file as the class)

<?php

class Test {
    private function
foo() {
        echo
"Foo" . PHP_EOL;
    }
    protected function
bar() {
        echo
"bar" . PHP_EOL;
    }

    static function
foobar($test) {
       
$test->bar(); // works
       
$test->foo(); // works
   
}   
}

function
simple_function() {
   
$test = new Test();

   
$test->bar(); // does not work

   
$test->foo(); // does not work
   
   
Test::foobar($test); // works
}

simple_function();
?>
up
-8
thcdesigning at gmail dot com
8 years ago
Private or not private?
I get baffled whenever I see this kind of an example.

<?php

class vessel{
    private
$things = array();
    
    public function
setThing($things){
           
$this->things = $things;
    }

    public function
getThing($obj){
        return
$obj->things;
    }
}

class
smallVessel{
    private
$things = array();
    
    public function
setThing($things){
           
$this->things = $things;
    }

    public function
getThing($obj){
        return
$obj->things;
    }
}

$basket = new vessel();
$bucket = new vessel();
$bowl = new smallVessel();

$basket->setThing(array('wine' , 'water' , 'sugar'));

// returns the contents inside basket unexpectedly
print_r($bucket->getThing($basket));

// returns error, quite rightly so!
print_r($bowl ->getThing($basket));
up
-7
aluciffer at hotmail dot com
8 years ago
As far as it regards the properties of objects, visibility is, yes, as the examples show.
Private, protected methods are not accessible via syntax $a->protectedVar, however their values are still (php 5.3.26) accessible through a number of other methods (serializing, converting to array, and nevertheless using the ReflectionClass methods).
As it was pointed out and such as in the example below:
<?php

echo "PHP Version: ".phpversion()."\n";

class
Foo
{
   private  
$bar  = "value of private var";
   protected
$bar2 = "value of protected var";
   public   
$bar3 = "value of public var";
}

$obj = new Foo;

echo
serialize($obj) . "\n";

print_r($obj);

print_r((array)$obj);

echo (
$obj->bar3) . "\n";
echo (
$obj->bar2) . "\n";
echo (
$obj->bar) . "\n";

?>

It will output:

PHP Version: 5.3.26
O:3:"Foo":3:{s:8:"Foobar";s:20:"value of private var ";s:7:"*bar2";s:22:"value of protected var";s:4:"bar3";s:19:"value of public var";}
Foo Object
(
    [bar:Foo:private] => value of private var
    [bar2:protected] => value of protected var
    [bar3] => value of public var
)

Array
(
    [Foobar] => value of private var
    [*bar2] => value of protected var
    [bar3] => value of public var
)
value of public var

While the last two lines, accessing directly the private and protected object properties (bar2 and bar), will throw out fatal errors like:
PHP Fatal error:  Cannot access private property Foo::$bar
and
PHP Fatal error:  Cannot access protected property Foo::$bar2
up
-2
tvitcom at yandex dot ru
1 year ago
<?php
//PHP Version 7.4.5 (compiled, as mod_cgi)

class BaseOne {
    public function Print(
$a) {
        return
$a . '123';
    }

    private function
PrintPrivate($a) {
        return
$a . '123';
    }

    protected function
PrintProtected($a) {
        return
$a . '123';
    }
}

class
BaseTwo extends BaseOne {}

$b = new BaseTwo();

echo
$b->Print('000');
echo
$b->PrintPrivate("000");//Fatal error: Uncaught Error: Call to private method BaseOne::PrintPrivate() from context...
echo $b->PrintProtected("000");//Fatal error: Uncaught Error: Call to protected method BaseOne::PrintProtected() from context...
up
-2
Patanjali
2 years ago
Re: wbcarts at juno dot com

Expected, since it comes down to PHP's lack of type enforcement.

Classes preserve structure, but doesn't natively enforce scalar property types, as per PHP's variables.

'It REQUIRES OUTSIDE CODE to do all the work...'

No, as you indicate, to mitigate this,  make variables private and use protected/public 'set' and 'get' types of methods to manipulate their values.

However, the 'set' functions would also need to enforce type and report errors if not of the correct type.

Of course, the code that uses classes should be designed to either:
a. Provide only the correct types of values.
b. Handle the errors reported.
c. Encapsulate use of the class with try-catch blocks.

Note that c. is what sloppy code feeding mistyped values to the class would have to do if type were strictly enforced.

Fortunately, as of 7.0, type can be specified for scalar function/method parameters, but would need try-catch blocks to handle mismatches from inside the class, rather than using the 'is' functions.

All of this is part of proper design and defensive programming.
up
-8
php at stage-slash-solutions dot com
10 years ago
access a protected property:

<?php

//Some library I am not allowed to change:

abstract class a
{
  protected
$foo;
}

class
aa extends a
{
  function
setFoo($afoo)
  {
     
$this->foo = $afoo;
  }
}

?>

if you get an instance of aa and need access to $foo:

<?php
class b extends a
{
  function
getFoo($ainstance)
  {
      return
$ainstance->foo;
  }
}

$aainstance=someexternalfunction();
$binstance=new b;
$aafoo=$binstance->getFoo($aainstance);
?>
up
-16
a dot schaffhirt at sedna-soft dot de
12 years ago
If you miss the "package" keyword in PHP in order to allow access between certain classes without their members being public, you can utilize the fact, that in PHP the protected keyword allows access to both subclasses and superclasses.

So you can use this simple pattern:

<?php
   
abstract class Dispatcher {
        protected function &
accessProperty (self $pObj, $pName) {
            return
$pObj->$pName;
        }
        protected function
invokeMethod ($pObj, $pName, $pArgs) {
            return
call_user_func_array(array($pObj, $pName), $pArgs);
        }
    }
?>

The classes that should be privileged to each other simply extend this dispatcher:

<?php
   
class Person extends Dispatcher {
        private
$name;
        protected
$phoneNumbers;
       
        public function
__construct ($pName) {
           
$this->name = $pName;
           
$this->phoneNumbers = array();
        }
        public function
addNumber (PhoneNumber $pNumber, $pLabel) {
           
$this->phoneNumbers[$pLabel] = $pNumber;

           
// this does not work, because "owner" is protected:
            // $pNumber->owner = $this;

            // instead, we get a reference from the dispatcher:
           
$p =& $this->accessProperty($pNumber, "owner");

           
// ... and change that:
           
$p = $this;                                   
        }
        public function
call ($pLabel) {
           
// this does not work since "call" is protected:
            // $this->phoneNumbers[$pLabel]->call();
           
            // instead, we dispatch the call request:
           
$this->invokeMethod($this->phoneNumbers[$pLabel], "call", array());
        }
    }
   
    class
PhoneNumber extends Dispatcher {
        private
$countryCode;
        private
$areaCode;
        private
$number;
        protected
$owner;
       
        public function
__construct ($pCountryCode, $pAreaCode, $pNumber) {
           
$this->countryCode = $pCountryCode;
           
$this->areaCode = $pAreaCode;
           
$this->number = $pNumber;
        }

        protected function
call () {
            echo(
"calling " . $this->countryCode . "-" . $this->areaCode . "-" . $this->number . "\n");
        }
    }

   
$person = new Person("John Doe");
   
$number1 = new PhoneNumber(12, 345, 67890);
   
$number2 = new PhoneNumber(34, 5678, 90123);
   
$person->addNumber($number1, "home");
   
$person->addNumber($number2, "office");
   
$person->call("home");
?>

Without this pattern you would have to make $owner and call() public in PhoneNumber.

Best regards,
up
-8
willbrownsberger at gmail dot com
6 years ago
Just wanted to share a trap for the unwary.  Where there are several layers of object assignments, setting the bottom object's properties as private will prevent its exposure.  However, if the bottom object has public properties, intermediate objects which are themselves set as private but are derived from the bottom object can inadvertently be exposed to updates. 

This follows logically from the reference model in php ( http://php.net/manual/en/language.oop5.references.php ), but can yield a result that is surprising until one gets the reference model.  The following example demonstrates the phenomenon.

// underlying class for offering database results to other objects
// __construct method yields public results -- bottom object in example

class database_result {
    public $column1;
    public function __construct() {
        // . . . database access . . .
        $this->column1 = 'foo';
    }
}

// application dictionary accesses database and caches results
// for application objects -- this is the second layer  in the example

class  dictionary {
    private $reference_object;
    public function __construct (){
        $this->reference_object = new database_result;
    }
   
    public function get_reference_object() {
        return ( $this->reference_object );
    }
}

$dictionary = new dictionary;
/* $dictionary->reference_object cannot be accessed directly
* $dictionary->reference_object->column1 = 'foochanged';
* yields Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
*/

$pointer_to_dictionary = $dictionary;
/*
* if assign $dictionary to new variable, the new variable is a pointer and its properties are still private
* $pointer_to_dictionary->reference_object->column1 = 'foochanged';
* Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
* $pointer_to_dictionary = $dictionary->reference_object;
*  Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
*/

//  now set up a client class that will use a working copy of the dictionary -- this is the third layer in the example

class dictionary_user {
    private $pointer_to_dictionary;
    public function __construct () {
        global $dictionary;
        // $this->pointer_to_dictionary = $dictionary->reference_object;
        // Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
        // still cannot directly access dictionary properties even in this context, except through getter
        $this->pointer_to_dictionary = $dictionary->get_reference_object();
    }

    // however, can now operate on dictionary through the pointer
    public function set_pointer_to_dictionary ( $value ) {
        $this->pointer_to_dictionary->column1 = $value;
    }
   
    public function get_pointer_to_reference_object(){
        return ($this->pointer_to_dictionary);   
    }
}

$dictionary_user = new dictionary_user;
$dictionary_user->set_pointer_to_dictionary ( 'foochanged' );
echo ('<br/>');
var_dump ( $dictionary_user->get_pointer_to_reference_object()); echo '<br/>';
// object(database_result)#2 (1) { ["column1"]=> string(10) "foochanged" } -- of course, the user object is changed
var_dump ( $dictionary->get_reference_object() );
// object(database_result)#2 (1) { ["column1"]=> string(10) "foochanged" }  -- however, the private dictionary object is also now corrupted!
// Note:  If the underlying database result object $column1 as private, this will cause set_pointer_to_dictionary to generate the usual fatal error
// but  making the bottom object private may defeat its purpose of exposing results.
up
-5
benjam
2 years ago
When overriding a private method with a more visible child method, the parent method may be called instead.

<?php

class Parent {
    private function
foo() {
        echo
"Parent Foo\n";
    }
   
    public function
call_foo() {
       
$this->foo();
    }
}

class
Child extends Parent {
    public function
foo() {
        echo
"Child Foo\n";
    }
}

$bar = new Child();
$bar->call_foo();
$bar->foo();

?>

will output:
Parent Foo
Child Foo
up
-13
noel darlow
6 years ago
After having the how explained, many people will still be left wondering about the why. How should the different kinds of visibility be used in practice?

Some kind of labelling for the public and private parts of an interface is certainly necessary. We need to be clear which methods will be part of the public interface and which are only used internally .

In older versions of php notionally-private functions were prefixed with an underscore - a much simpler and more elegant solution to the labelling problem. "Protected" adds clutter which affects readability. It adds a lot of unnecessary typing to what is already a keyboard-intensive job.

As for enforcement.. no-one ever got mixed up about public/private so long as they were clearly labelled. As such, "protected" is an attempt to solve a problem which simply did not exist.

Private is even worse. It specifically encourages bad object-oriented code with the use of inheritance in places where you should be thinking about separate, co-operating objects.

A feeling that classes which inherit from each other need to hide some of their bits from each other is a sure sign that you need to break the code up into separate objects. This is exactly what encapsulation is for. It doesn't make any sense to try to encapsulate bits inside an inheritance tree. Classes which extend other classes must always be free to override whatever it is they need to override in their parent classes.

In short, use protected if you must, do not use private at all. Do not try to squeeze too much new functionality into an inheritance tree: create networks of co-operating objects with clearly-defined responsibilities instead.

It's a real shame that php took the decision to implement private and protected. They add nothing to our ability to write good quality OO code; they simply make that code more difficult to write and to understand.   Clarity and simplicity are incredibly important in programming but now both php programmers and php developers are stuck with these unnecessary layers of complexity.
up
-12
gried at NOSPAM dot nsys dot by
6 years ago
I want to merge notes from different comments about visibility of class members from parent class / sibling class point of view because visibility rules are similar. Here are main points:
    1. Methods declared in parent class can access some child class members.
    2. Class can access some sibling class members using methods declared in common parent. NB: only inherited not-overridden parent method could be used, if you override it in current class you have to call parent method statically to get access to sibling members.

You can see list of members that could be accessed via these methods below:
- inherited protected / private property – OK;
- inherited protected / private method without overriding – OK;
- inherited protected method with overriding – OK;
- inherited private method with overriding – FAIL, original parent method will be called;
- own protected property / method – OK;
- own private property / method – FAIL, critical error.

官方地址:https://www.php.net/manual/en/language.oop5.visibility.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3