PHP. OOP. Propepties and methods scope

Home » Tutorials » PHP » PHP. OOP. Properties and methods scope
We continue to learn basic principles of OOP in PHP. Today we will discuss properties/methods scope. There three modifiers in PHP:

  • public – public properties/methods can be accessed anywhere.
  • protected – protected properties/methods can be accessed in class and child classes.
  • private – private properties/methods can be accessed in which class they have been declared .
If you don’t set modifier directly for property or method, it will be as public in code. Also I notice, protected and public proreprties/methods can’t be accessed in object context.
You can read about scope in details on official php site by this link.
Code lesson
<?php
/*
** Область видимости
** Нельзя переопределить private в дочерних классах
**/

class Man {

    public $name = "Камиль";
    protected $surname = "Абзалов";
    private $age = 27;

    public function printInfo() {
        echo $this->name . " " . $this->surname . " " . $this->age;
    }

    protected function printProtected() {
        echo "Вызов protected метода";
    }

    protected function printPrivate() {
        echo "Вызов private метода";
    }

}

class Kamil extends Man {

    public $name = "Еще один Камиль";
    protected $surname = "c фамилией Абзалов";

}

$man = new Man();
$kamil = new Kamil();


print_r($man);
echo "<br>";

print_r($kamil);
echo "<br>";

echo $man->name;
echo "<br>";
/*echo $man->surname;
echo "<br>";
echo $man->age;
echo "<br>";*/

echo $kamil->name;
echo "<br>";
/*echo $kamil->surname;
echo "<br>";
echo $kamil->age;*/


echo $man->printInfo();
echo "<br>";

/*echo $man->printProtected();
echo "<br>";

echo $man->printPrivate();
echo "<br>"; */

echo $kamil->printInfo();
echo "<br>";

/*echo $man->printProtected();
echo "<br>";

echo $man->printPrivate();
echo "<br>"; */

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This