Php когда использовать private

Приватные классы. Сокрытие в php

В php как и в большинстве других ООП языков существуют модификаторы видимости. Это ключевые слова public, protected и private. Но они применимы исключительно к свойствам, методам или константам. Данные модификаторы тесно связаны с возможностью инкапсуляции данных. Стоит заметить, что в таких языках как java, C#, go (https://golang.org/doc/go1.4#internalpackages), ruby (https://habr.com/post/419969/), crystal (https://crystal-lang.org/reference/syntax_and_semantics/visibility.html) есть возможность ограничивать область видимость пакетов (packages) или классов\типов. В php нет возможности ограничивать область видимости для классов — любой подключенный класс доступен из любого другого класса. Однако можно эмулировать данную возможность с применением нескольких трюков.

Для чего вообще может понадобиться сокрытие на уровне классов:

  • Служебные классы (хелперы) библиотеки — не замусориваем API библиотеки не имеющими смысла internal классами.
  • Инкапсуляция с сокрытием внутренних объектов «бизнес логики», например запрет прямого порождения зависимых объектов в обход более общего класса.

Отдельно можно выделить разбиение «больших» классов на мелкие объекты. Хорошей практикой считается ограничивать сложность (и количество строк) как отдельных методов так и классов. Количество строк тут идёт как один из маркеров, что метод класса или сам класс берёт на себя лишнию ответственность. При рефакторинге public метода мы выносим его части в private\protected методы. Но когда по тем или иным причинам класс разрастается и мы выделяем из него отдельную сущность, эти самые private\protected классы переносятся в отдельный класс, тем самым мы косвенно открываем доступ к методам, которые ранее были ограничены областью видимости одного класса.

Читайте также:  Php change ad user password

Теперь собственно сами способы эмуляции сокрытия.

На уровне соглашения оформления кода

Используя PHPDoc комментарии можно отметить класс, трэйт или интерфейс как internal (http://docs.phpdoc.org/references/phpdoc/tags/internal.html). При этом некоторые IDE (например PhpStorm) могут понимать такие метки.

Использовать runtime информацию

Во время исполнения кода можно проверить откуда был вызван конструктор класса. Например через метод debug_backtrace (http://php.net/manual/ru/function.debug-backtrace.php) или использовать аналогичный функционал Xdebug для контроля кода в dev\test окружении. Пример оформленного решения есть тут (https://coderwall.com/p/ixvnga/how-emulates-private-class-concept-in-php).

/** * The private class */ final class PrivateClass < /** * defines the only class able to instantiate the current one * * @var string */ private $allowedConsumer = 'AllowedPrivateClassConsumer'; /** * constructor * * @throws Exception */ public function __construct() < /** * here comes the privacy filter, it could be extracted to a private method * or to a static method of another class with few adjustments */ $builder = debug_backtrace(); if (count($builder) < 2 || !isset($builder[1]['class']) || $builder[1]['class'] !== $this->allowedConsumer) < throw new Exception('Need to be instantiated by '.$this->allowedConsumer); > > >

Использовать анонимные классы

Относительно новый функционал в php — анонимные классы (http://php.net/manual/ru/language.oop5.anonymous.php). Описав анонимный класс внутри защищенного метода мы добиваемся его сокрытия. Что бы не городить портянку определения класса внутри функции, можно описать «приватный» класс в отдельном файле как абстрактный, и уже расширять его в определении анонимного класса. Хороший пример использования данного метода есть по этой ссылке (https://markbakeruk.net/2018/06/25/using-php-anonymous-classes-as-package-private-classes/).

Исходя из найденного материала видно, что функционал сокрытия классов в какой то мере востребован (и существует во многих языках), однако практика его использования очень ограничена, возможно отсутствием описанием примеров в различных «best practices», сборников шаблонов и подобных источниках. Что на мой взгляд является довольно странным, что есть акцентирование на сокрытие внутренних методов и свойств объектов, но почти никто не обращает внимание, что более крупные логические куски кода в виде служебных классов библиотек или доменной области остаются в глобальном пространстве видимости.

Читайте также:  Python call super method

Источник

Access Modifiers in PHP

In PHP, access modifiers are an important part of object-oriented programming (OOP). They specify the scope of class variables or methods and how they can be accessed. In this post, we will look at the different types of access modifiers in PHP and offer examples of how to use them.

Access Modifier Types in PHP

In PHP, access modifiers are classified as public, private, or protected.

  • Public: A method or attribute that is set to public can be accessed everywhere. This is the default access modifier in PHP.
  • Private: A method or attribute that is set to private can only be accessed within the class in which it is created.
  • Protected: A method or attribute that is set to protected can be accessed within the class in which it is created, as well as in classes that inherit from that class.
class Person < public $name; protected $age; private $height; >$x= new Person(); $x->name = 'John'; // OK $x->age= '32'; // ERROR $x->height= '5.4'; // ERROR

In the above example, we define a “Person” class with three attributes, each with a separate access modifier. The “name” attribute is public, the “age” attribute is protected, and the “height” attribute is private. When we try to access the “name” attribute outside of the class and add a value to it, everything works fine. However, attempting to add values to the “age” and “height” properties outside of the class results in a fatal error.

Public, Private, and Protected Methods

class Person< public $name; public $age; public $height; function set_name($n) < // a public function (default) $this->name = $n; > protected function set_age($a) < // a protected function $this->age = $a; > private function set_height($h) < // a private function $this->height = $h; > > $person = new Person(); $person->set_name('John'); // OK $person->set_age('26'); // ERROR $person->set_height('5.4'); // ERROR

In the above example, we build a “Person” class with three methods, each with a separate access modifier. The “set name” method is public, the “set age” method is protected, and the “set height” method is private. When we try to invoke the “set name” function from outside the class, it works well. When we try to call the “set age” and “set height” methods from outside the class, we get a fatal error.

Advanced Access Modifiers: Abstract and Final

PHP provides sophisticated access modifiers named “abstract” and “final” in addition to the regular access modifiers.

  • An abstract access modifier can only be used on classes and methods. It is used to construct a class blueprint, however the class cannot be instantiated. Abstract methods are methods that every class that inherits from the abstract class must implement.
  • Classes, methods, and properties can all be given a final access modifier. It is used to prohibit a class or method from being extended or overridden.
abstract class Bike < private $maxSpeed = 80; // Simple method public function drivingSpeed() < return "Driving at " . $this->maxSpeed . " kilometer/hour"; > // Abstract method abstract public function drive(); > class Police extends Bike < public function drive() < return "Driving out of speed limit."; >> $bike= new Police(); echo $bike->drivingSpeed();

In the example above, we build an abstract class named “Bike” that has an abstract function called “drive()”. We next construct a new class named “Police,” which extends the “Bike” class and implements the “drive()” function. We use the “Police” class instead because we can’t build an object of the abstract class.

Finally, access modifiers are an important part of OOP in PHP and are used to limit the scope of class variables or functions. Understanding and effectively using access modifiers may help you develop more secure and maintainable code.

Q&A

Q: What are access modifiers?
A: Access modifiers define the scope of class variables or methods, as well as where they may be accessed. In PHP, access modifiers are classified as public, private, or protected.

Q: What is the default access modifier?
A: PHP’s default access modifier is public. If you do not provide the access modifier while creating a method or attribute in a PHP class, it is set to public by default.

Q: What is the difference between private and protected access modifiers?
A: A private method or attribute may only be accessible within the class that generated it, but a protected method or attribute can be accessed within the class that created it as well as classes that inherited from that class.

Q: Can you give an example of using an abstract access modifier in PHP?

abstract class Bike < private $maxSpeed = 80; abstract public function drive(); >class Police extends Bike < public function drive() < return "Driving out of speed limit."; >>

In the example above, we build an abstract class named “Bike” that has an abstract function called “drive()”. We next construct a new class named “Police,” which extends the “Bike” class and implements the “drive()” function. We use the “Police” class instead because we can’t build an object of the abstract class.

Q: How does the final access modifier work?
A: The final access modifier can be applied to classes, methods, and properties. It is used to prevent a class from being extended or a method from being overridden. This means that any class that inherits from a final class cannot be extended, and any method that is marked as final cannot be overridden.

Exercises:

  1. What is the default access modifier in PHP?
  2. What is the difference between private and protected access modifiers in PHP?
  3. Give an example of using an abstract access modifier in PHP.
  4. How does the final access modifier work?
  5. Can you create an object of an abstract class? Why or why not?
  6. Can you override a final method in a child class? Why or why not?
  7. Can you assign a value to a private attribute outside of the class in which it is created? Why or why not?
  8. Can a protected method be accessed outside of the class in which it is created? Why or why not?

Answers:

  1. The default access modifier in PHP is public.
  2. A private method or attribute in PHP can only be accessed within the class in which it is created, whereas a protected method or attribute can be accessed within the class in which it is created, as well as in classes that inherit from that class.
abstract class Bike < private $maxSpeed = 80; abstract public function drive(); >class Police extends Bike < public function drive() < return "Driving out of speed limit."; >>

4. The final access modifier can be applied to classes, methods, and properties. It is used to prevent a class from being extended or a method from being overridden.
5. No, we cannot create an object of an abstract class because an abstract class serves as a blueprint for other classes and does not have a constructor to create an object.
6. No, we cannot override a final method in a child class as it is marked as final and cannot be overridden.
7. No, we cannot provide a value to a private attribute outside of the class that generated it since the attribute is only available within the class.
8. No, a protected method cannot be accessible outside of the class that created it, but it may be accessed by classes that derive from that class.

Источник

Оцените статью