Область видимости

Область видимости свойства или метода может быть определена путем использования следующих ключевых слов в объявлении: public, protected или private. Доступ к свойствам и методам класса, объявленным как public (общедоступный), разрешен отовсюду. Модификатор protected (защищенный) разрешает доступ наследуемым и родительским классам. Модификатор private (закрытый) ограничивает область видимости так, что только класс, где объявлен сам элемент, имеет к нему доступ.

Область видимости свойства

Свойства класса должны быть определены через модификаторы public, private, или protected. Если же свойство определено с помощью var, то оно будет доступно как public свойство.

Пример #1 Объявление свойства класса


Наш Telegram бот: @htmlweb_bot
/**
 * Определение MyClass
 */
class MyClass
{
    public $public = 'Общий';
    protected $protected = 'Защищенный';
    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(); // Выводит Общий, Защищенный и Закрытый
/**
 * Определение MyClass2
 */
class MyClass2 extends MyClass
{
    // Мы можем переопределить public и protected методы, но не private
    protected $protected = 'Защищенный2';
    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}
$obj2 = new MyClass2();
echo $obj2->public; // Работает
echo $obj2->private; // Неопределен
echo $obj2->protected; // Неисправимая ошибка
$obj2->printHello(); // Выводит Общий, Защищенный2 и Неопределен

Замечание: Метод объявления переменной через ключевое слово var, принятый в PHP 4, до сих пор поддерживается в целях совместимости (как синоним ключевого слова public). В версиях PHP 5 ниже 5.1.3 такое использование выводит предупреждение E_STRICT.


Область видимости метода

Методы класса должны быть определены через модификаторы public, private, или protected. Методы, где определение модификатора отсутствует, определяются как public.

Пример #2 Объявление метода

/**
 * Определение 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(); // Работает общий, защищенный и закрытый
/**
 * Определение 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


Видимость из других объектов

Объекты одного типа имеют доступ к элементам с модификаторами private и protected друг друга, даже если не являются одним и тем же экземпляром. Это объясняется тем, что реализация видимости элементов известна внутри этих объектов.

Пример #3 Доступ к элементам с модификатором private из объектов одного типа

class Test
{
    private $foo;
    public function __construct($foo)
    {
        $this->foo = $foo;
    }
    private function bar()
    {
        echo 'Доступ к закрытому методу.';
    }
    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"
Доступ к закрытому методу.

User Contributed Notes 17 notes



30
wbcarts at juno dot com1 year ago
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;


7
what at ever dot com4 years ago
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();


3
omega at 2093 dot es1 year ago
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');


3
IgelHaut1 year ago
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);


3
andrei at leapingbytes dot net11 months ago
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();


3
r dot wilczek at web-appz dot de7 years ago
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


1
alexaulbach at mayflower dot de1 year ago
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();


1
Marce!4 years ago
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


0
briank at kappacs dot com2 years ago
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


0
php at stage-slash-solutions dot com2 years ago
//Some library I am not allowed to change:
abstract class a
{
  protected $foo;
}
class aa extends a
{
  function setFoo($afoo)
  {
      $this->foo = $afoo;
  }
}


0
a dot schaffhirt at sedna-soft dot de4 years ago
    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);
        }
    }


0
stephane at harobed dot org7 years ago
class A {
    private function foo()
    {
        print("bar");
    }
    static public function bar($a)
    {
        $a->foo();
    }
}
$a = new A();
A::bar($a);


-1
jc dot flash at gmail dot com1 year ago
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


-1
imran at phptrack dot com4 years ago
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)); 
 
0 
 aluciffer at hotmail dot com ¶4 months 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";


0
Joshua Watt6 years ago
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




Смотрите также:
Описание на ru2.php.net
Описание на php.ru