类与对象
在线手册:中文  英文

访问控制(可见性)

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

属性的访问控制

类属性必须定义为公有,受保护,私有之一。如果用 var 定义,则被视为公有。

Example #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 而不能
    
protected $protected 'Protected2';

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

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

?>

Note: 为了兼容性考虑,在 PHP 4 中使用 var 关键字对变量进行定义的方法在 PHP 5 中仍然有效(只是作为 public 关键字的一个别名)。在 PHP 5.1.3 之前的版本,该语法会产生一个 E_STRICT 警告。

方法的访问控制

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

Example #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
?>

其它对象的访问控制

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

Example #3 访问同一个对象类型的私有成员

<?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)
    {
        
// We can change the private property:
        
$other->foo 'hello';
        
var_dump($other->foo);

        
// We can also call the private method:
        
$other->bar();
    }
}

$test = new Test('test');

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

以上例程会输出:

string(5) "hello"
Accessed the private method.

类与对象
在线手册:中文  英文

用户评论:

andrei at leapingbytes dot net (2012-12-20 09:50:54)

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();
?>

alexaulbach at mayflower dot de (2012-11-06 13:32:34)

<?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 
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.

omega at 2093 dot es (2012-07-06 12:04:51)

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.

jc dot flash at gmail dot com (2012-06-21 02:31:23)

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
?>

IgelHaut (2012-05-30 13:48:51)

<?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.

wbcarts at juno dot com (2012-05-19 20:27:17)

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!

briank at kappacs dot com (2011-11-10 12:20:08)

To make (some) object members read-only outside of the class (revisited using PHP 5 magic __get):

<?php

class ReadOnlyMembers {

    private 
$reallyPrivate;
    private 
$justReadOnly;

    function 
__construct () {
        
$this->reallyPrivate 'secret';
        
$this->justReadOnly 'read only';
    }

    function 
__get ($what) {
        switch (
$what) {
        case 
'justReadOnly':
            return 
$this->$what;

        default:
            
# Generate an error, throw an exception, or ...
            
return null;
        }
    }

    function 
__isset ($what) {
        
$val $this->__get($what);
        return isset(
$val);
    }

}

$rom = new ReadOnlyMembers();

var_dump($rom->justReadOnly);           // string(9) "read only"

$rom->justReadOnly 'new value';       // Fatal error

var_dump($rom->reallyPrivate);          // Fatal error

?>

php at stage-slash-solutions dot com (2011-07-10 15:21:59)

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 extends a
{
  function 
getFoo($ainstance)
  {
      return 
$ainstance->foo;
  }
}

$aainstance=someexternalfunction();
$binstance=new b;
$aafoo=$binstance->getFoo($aainstance);
?>

Marce! (2009-09-25 03:04:23)

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
?>

imran at phptrack dot com (2009-08-18 14:06:14)

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)

a dot schaffhirt at sedna-soft dot de (2009-06-29 00:27:58)

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(1234567890);
    
$number2 = new PhoneNumber(34567890123);
    
$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,

what at ever dot com (2008-12-04 05:15:17)

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".

Jeffrey (2008-10-09 17:48:03)

WHEN do I use public, protected or private keyword? Here's the default behavior.
<?php
class Example
{
  
/* use PUBLIC on variables and functions when:
   *  1. outside-code SHOULD access this property or function.
   *  2. extending classes SHOULD inherit this property or function.
   */  
  
public $var1;
  public function 
someFunction_1() { }

  
/* use PROTECTED on variables and functions when:
   *  1. outside-code SHOULD NOT access this property or function.
   *  2. extending classes SHOULD inherit this property or function.
   */
  
protected $var2;
  protected function 
someFunction_2() { }

  
/* use PRIVATE on variables and functions when:
   *  1. outside-code SHOULD NOT access this property or function.
   *  2. extending classes SHOULD NOT inherit this property or function.
   */
  
private $var3;
  private function 
someFunction_3() { }
}

# these are the only valid calls outside-code can make on Example objects:
 
$obj1 = new Example();      // instantiate
 
$var1 $obj1->var1;        //  get public data
 
$obj1->var1 35;           //  set public data
 
$obj1->someFunction_1();    // call public function
?>

Now try extending the class...

<?php
class Example_2 extends Example
{
  
// this class inherits the following properties and functions.
  
public $var1;
  public function 
someFunction_1() { }
  protected 
$var2;
  protected function 
someFunction_2() { }
}

# these are the only valid calls outside-code can make on Example_2 objects:
 
$obj2 = new Example_2();  // instantiate
 
$var2 $obj2->var1;      //  get public data
 
$obj2->var1 45;         //  set public data
 
$obj2->someFunction_1();  // call public function
?>

wbcarts at juno dot com (2008-09-10 14:21:33)

UNDERSTANDING PHP's OBJECT VISIBILITY

Sometimes it's good to see a list of many extended classes, one right after the other - just for the sole purpose of looking at their inherited members. Maybe this will help:

<?php
class MyClass_1{
    public 
$pubVal 'Hello World!';
    protected 
$proVal 'Hello FROM MyClass_1';
    private 
$priVal 'Hello TO MyClass_1';

    public function 
__toString(){
        return 
"MyClass_1[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class 
MyClass_2 extends MyClass_1{
    public function 
__toString(){
        return 
"MyClass_2[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class 
MyClass_3 extends MyClass_2{
    private 
$priVal 'Hello TO MyClass_3';

    public function 
__toString(){
        return 
"MyClass_3[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class 
MyClass_4 extends MyClass_3{
    protected 
$proVal 'Hello FROM MyClass_4';

    public function 
__toString(){
        return 
"MyClass_4[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class 
MyClass_5 extends MyClass_4{
    public function 
__toString(){
        return 
"MyClass_5[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

class 
MyClass_6 extends MyClass_5{
    private 
$priVal 'Hello TO MyClass_6';

    public function 
__toString(){
        return 
"MyClass_6[public=$this->pubVal, protected=$this->proVal, private=$this->priVal]";
    }
}

echo (new 
MyClass_1()) . '<br>';
echo (new 
MyClass_2()) . '<br>';
echo (new 
MyClass_3()) . '<br>';
echo (new 
MyClass_4()) . '<br>';
echo (new 
MyClass_5()) . '<br>';
echo (new 
MyClass_6()) . '<br>';
?>

The list of extended objects:

 MyClass_1[public=Hello World!, protected=Hello FROM MyClass_1, private=Hello TO MyClass_1]
 MyClass_2[public=Hello World!, protected=Hello FROM MyClass_1, private=]
 MyClass_3[public=Hello World!, protected=Hello FROM MyClass_1, private=Hello TO MyClass_3]
 MyClass_4[public=Hello World!, protected=Hello FROM MyClass_4, private=]
 MyClass_5[public=Hello World!, protected=Hello FROM MyClass_4, private=]
 MyClass_6[public=Hello World!, protected=Hello FROM MyClass_4, private=Hello TO MyClass_6]

Notice in the class definitions, I made absolutly no attempt to change protected members to private, etc. - that gets too confusing and is not necessary - though I did redeclare a few members with the same var name and visibility strength. One other noteworthy: the output for MyClass_2, there seems to be a private property with value of empty string. Here, $priVal was not inherited from MyClass_1 because it is private in MyClass_1, instead, because of PHP's relaxed syntax, it was actually created right there in MyClass2::__toString() method... not only that, it is not a private member either. Watch out for this kind of thing, as PHP can sometimes give confusing impressions.

omnibus at omnibus dot edu dot pl (2007-12-13 06:34:35)

Please note that if a class has a protected variable, a subclass cannot have the same variable redefined private (must be protected or weaker). It seemed to be logical for me as a subsubclass would not know if it could see it or not but even if you declare a subclass to be final the restriction remains.

phpdoc at povaddict dot com dot ar (2007-10-11 12:52:57)

Re: ference at super_delete_brose dot co dot uk

"If eval() is the answer, you’re almost certainly asking the wrong question."

<?php
eval('$result = $this->'.$var.';'); //wrong
$result $this->$var//right way

$var "foo";
$this->var "this will assign to member called 'var'.";
$this->$var "this will assign to member called 'foo'.";
?>

Joshua Watt (2007-05-29 12:09:08)

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 
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
?>

ference at super_delete_brose dot co dot uk (2007-05-22 10:10:09)

Sometimes you may wish to have all members of a class visible to other classes, but not editable - effectively read-only.

In this case defining them as public or protected is no good, but defining them as private is too strict and by convention requires you to write accessor functions.

Here is the lazy way, using one get function for accessing any of the variables:

<?php

class Foo {

  private 
$a;
  private 
$b;
  private 
$c;
  private 
$d;
  private 
$e;
  private 
$f;

  public function 
__construct() {
    
$this->'Value of $a';
    
$this->'Value of $b';
    
$this->'Value of $c';
    
$this->'Value of $d';
    
$this->'Value of $e';
    
$this->'Value of $f';
  }

  
/* Accessor for all class variables. */
  
public function get($what) {
    
$result FALSE;
    
$vars array_keys(get_class_vars('Foo'));

    foreach (
$vars as $var) {
      if (
$what == $var) {
        eval(
'$result = $this->'.$var.';');
        return 
$result;
      }
    }
    return 
$result;
  }
}

class 
Bar {
  private 
$a;

  public function 
__construct() {
    
$foo = new Foo();

    
var_dump($foo->get('a'));     // results in: string(11) "Value of $a"
  
}
}

$bar = new Bar();

?>

nanocaiordo at gmail dot com (2007-04-08 06:49:37)

If you always thought how can you use a private method in php4 classes then try the following within your class.

<?php
function private_func($func)
{
    
$this->file __FILE__;
    if (
PHPVERS >= 43) {
        
$tmp debug_backtrace();
        for (
$i=0$i<count($tmp); ++$i) {
            if (isset(
$tmp[$i]['function'][$func])) {
                if (
$this->file != $tmp[$i]['file']) {
                    
trigger_error('Call to a private method '.__CLASS__.'::'.$func.' in '.$tmp[$i]['file'], E_USER_ERROR);
                }
            }
        }
    }
}
?>

Then inside the private function add:
<?php
function foo() {
    
$this->private_func(__FUNCTION__);
    
# your staff goes here
}
?>

stephane at harobed dot org (2006-08-23 02:22:49)

A class A static public function can access to class A private function :

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

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

$a = new A();

A::bar($a);
?>

It's working.

kakugo at kakugo dot com (2006-07-13 03:19:13)

This refers to previous notes on protected members being manipulated externally:
It is obvious that if you were to allow methods the option of replacing protected variables with external ones it will be possible, but there is no reason not to simply use a protected method to define these, or not to write the code to allow it. Just because it is possible doesn't mean it's a problem, it simply does not allow you to be lax on the security of the class.

r dot wilczek at web-appz dot de (2006-01-05 05:11:33)

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($b3);
$b->setForeignBar($a4);
$a->debugBar($b);        // 3
$b->debugBar($a);        // 4
?>

gugglegum at gmail dot com (2005-09-02 03:14:49)

Private visibility actually force members to be not inherited instead of limit its visibility. There is a small nuance that allows you to redeclare private member in child classes.

<?php

class A
{
private 
$prop 'I am property of A!';
}

class 
extends A
{
public 
$prop 'I am property of B!';
}

$b = new B();
echo 
$b->prop// "I am property of B!"

?>

Miguel <miguel at lugopolis dot net> (2005-07-21 08:10:24)

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:

<?php
class {
    private 
$_myPrivate="private";

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

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

$obj=new B();
$obj->show(); // shows "private\n";
?>

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

易百教程