Может ли абстрактный класс содержать частный метод php

Возможно ли иметь частный конкретный метод внутри абстрактного класса в Php.

абстрактные методы не могут быть приватными. Либо публично, либо защищено — это нормально. Если вы используете IDE для разработки, вы увидите точную причину, по которой методы в абстрактных классах не могут быть закрытыми

1 ответ

TL; DR: да, вы можете.

abstract class Foo < private function test() < echo 'abstract private' . PHP_EOL; >public function useTest() < $this->test(); > > class Bar extends Foo <> $x = new Bar; $x->useTest(); 

Но этот частный метод будет отображаться ТОЛЬКО этому абстрактному классу. Это означает, что он должен будет использоваться каким-либо другим конкретным методом в абстрактном классе (с защитой видимости общественности).

Детские классы не смогут вызвать его напрямую.

Ещё вопросы

  • 1 Как получить текущий элемент в Dropdownlist для ASP.NET
  • 1 Принесите вперед некоторые маркеры круга в особенность листовки
  • 1 Как вы печатаете сообщение об ошибке при попытке ввести отрицательное значение в массив?
  • 1 событие android onClick не запускается
  • 1 Какой фильтр для кодирования PNG чересстрочной с использованием компонентов обработки изображений Windows (WIC) с оболочкой C #?
  • 0 Ошибка восстановления поверхности — PCL 1.6
  • 0 Внедренное видео в ios, предотвращающее функциональность navbar jquery mobile
  • 0 r-mysql: используйте переменную r для извлечения столбца из базы данных
  • 1 Как хранить неживые предметы
  • 0 PHP парсинг XML
  • 0 пакет udp не получен в QThread
  • 1 GWT сериализует класс, расширяющий TreeSet
  • 0 Вызов ActionResult из события OnChange [MVC4]
  • 0 scanf может читать только 3 символа в 5-позиционном массиве символов
  • 0 Разница между методами clear () и erase () вектора в c ++?
  • 0 Встроенное переполнение: скрыто, только частично работает
  • 0 Вызов метода контроллера из CUserIdentity
  • 1 Как проверить массив на возможные делители?
  • 1 Android: как подключить Studio к виртуальному устройству Genymotion?
  • 1 C # Сделать фон формы прозрачным (для отображения фона .png с полупрозрачными пикселями)
  • 0 JQuery класс переключения на клик
  • 1 Какая разница между решениями проблемы «текстовая коммуникация не разрешена»
  • 1 Уведомления не получаются на устройство, но получают успех на FCM, в чем проблема?
  • 0 Обновить / реинициализировать домашнюю страницу — Angular JS
  • 0 MySQL неизвестный столбец в моем запросе
  • 1 Не удается создать NotificationCompat.Builder в Android O
  • 1 Рельсы — относительные пути — методы
  • 1 Python OpenCV предупреждение libpng: iCCP: известен неправильный профиль sRGB
  • 0 SHOW CREATE PROCEDURE имя_процесса не отображает содержание процедуры
  • 1 Ошибка WSGI при переносе приложения Python / Flask из Heroku в Azure
  • 1 Как удалить конкретное значение из списка массивов, а также его следующие два значения на основе одного условия, используя итератор над массивом?
  • 1 получение того же типа унаследованных элементов класса из списка базовых классов с помощью linq
  • 0 привязка события click к jqzoom для запуска fancybox
  • 0 Зеркало сортируемого списка пользовательского интерфейса jQuery
  • 0 Отключение веб-API Asp.net Identity 2 от проекта?
  • 1 Как сохранить клавиатуру InputField открытой при потере фокуса?
  • 1 как подстроку строки при поиске определенного имени?
  • 1 тип безопасности (mypy) для параметров функции при использовании * args
  • 0 _DEBUG и LLVM 5.0 C ++: ожидаемое значение препроцессора в выражении
  • 1 Есть ли Java-эквивалент службы Windows
  • 0 AngularJS: Как мне прокрутить объект со смещением?
  • 1 Почему деление исключений во время компиляции на ноль не производит в Eclipse IDE?
  • 0 дополнительные элементы данных в объединенной структуре
  • 0 Разложение LU в c ++ не работает на больших матрицах
  • 1 Как отключить макет обновления смахивания, когда RecyclerView не на первом элементе?
  • 0 Центрирование растрового текста в прямоугольнике с помощью OpenGL
  • 1 await CLGeocoder.GeocodeAddressAsync никогда не возвращается
  • 1 Захват изображений со смешанными изображениями в Nokia Imaging SDK
  • 1 Почему мой массив не усредняет все числа?
  • 1 Скрипт копирования файлов Python
Читайте также:  Install python requests linux

Источник

Может ли абстрактный класс содержать частный метод php

This example will hopefully help you see how abstract works, how interfaces work, and how they can work together. This example will also work/compile on PHP7, the others were typed live in the form and may work but the last one was made/tested for real:

// Define things a product *has* to be able to do (has to implement)
interface productInterface public function doSell ();
public function doBuy ();
>

// Define our default abstraction
abstract class defaultProductAbstraction implements productInterface private $_bought = false ;
private $_sold = false ;
abstract public function doMore ();
public function doSell () /* the default implementation */
$this -> _sold = true ;
echo «defaultProductAbstraction doSell: < $this ->_sold > » . ¶ ;
>
public function doBuy () $this -> _bought = true ;
echo «defaultProductAbstraction doBuy: < $this ->_bought > » . ¶ ;
>
>

class defaultProductImplementation extends defaultProductAbstraction public function doMore () echo «defaultProductImplementation doMore()» . ¶ ;
>
>

class myProductImplementation extends defaultProductAbstraction public function doMore () echo «myProductImplementation doMore() does more!» . ¶ ;
>
public function doBuy () echo «myProductImplementation’s doBuy() and also my parent’s dubai()» . ¶ ;
parent :: doBuy ();
>
>

class myProduct extends defaultProductImplementation private $_bought = true ;
public function __construct () var_dump ( $this -> _bought );
>
public function doBuy () /* non-default doBuy implementation */
$this -> _bought = true ;
echo «myProduct overrides the defaultProductImplementation’s doBuy() here < $this ->_bought > » . ¶ ;
>
>

class myOtherProduct extends myProductImplementation public function doBuy () echo «myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too» . ¶ ;
parent :: doBuy ();
>
>

echo «new myProduct()» . ¶ ;
$product = new myProduct ();

$product -> doBuy ();
$product -> doSell ();
$product -> doMore ();

echo ¶ . «new defaultProductImplementation()» . ¶ ;

$newProduct = new defaultProductImplementation ();
$newProduct -> doBuy ();
$newProduct -> doSell ();
$newProduct -> doMore ();

echo ¶ . «new myProductImplementation» . ¶ ;
$lastProduct = new myProductImplementation ();
$lastProduct -> doBuy ();
$lastProduct -> doSell ();
$lastProduct -> doMore ();

echo ¶ . «new myOtherProduct» . ¶ ;
$anotherNewProduct = new myOtherProduct ();
$anotherNewProduct -> doBuy ();
$anotherNewProduct -> doSell ();
$anotherNewProduct -> doMore ();
?>

Will result in:
/*
new myProduct()
bool(true)
myProduct overrides the defaultProductImplementation’s doBuy() here 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()

new defaultProductImplementation()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()

new myProductImplementation
myProductImplementation’s doBuy() and also my parent’s dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!

new myOtherProduct
myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too
myProductImplementation’s doBuy() and also my parent’s dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!

Also you may set return/arguments type declaring for abstract methods (PHP>=7.0)
declare( strict_types = 1 );

abstract class Adapter
protected $name ;
abstract public function getName (): string ;
abstract public function setName ( string $value );
>

class AdapterFoo extends Adapter
public function getName (): string
return $this -> name ;
>
// return type declaring not defined in abstract class, set here
public function setName ( string $value ): self
$this -> name = $value ;
return $this ;
>
>
?>

The documentation says: «It is not allowed to create an instance of a class that has been defined as abstract.». It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:
abstract class Foo
static function bar ()
echo «test\n» ;
>
>

Here is another thing about abstract class and interface.

Sometimes, we define an interface for a `Factory` and ease out some common methods of the `Factory` through an `abstract` class.

In this case, the abstract class implements the interface, but does not need to implement all methods of the interface.

The simple reason is, any class implementing an interface, needs to either implement all methods, or declare itself abstract.

Because of this, the following code is perfectly ok.

interface Element /**
* Constructor function. Must pass existing config, or leave as
* is for new element, where the default will be used instead.
*
* @param array $config Element configuration.
*/
public function __construct ( $config = [] );

/**
* Get the definition of the Element.
*
* @return array An array with ‘title’, ‘description’ and ‘type’
*/
public static function get_definition ();

/**
* Get Element config variable.
*
* @return array Associative array of Element Config.
*/
public function get_config ();

/**
* Set Element config variable.
*
* @param array $config New configuration variable.
*
* @return void
*/
public function set_config ( $config );
>

abstract class Base implements Element

/**
* Element configuration variable
*
* @var array
*/
protected $config = [];

/**
* Get Element config variable.
*
* @return array Associative array of Element Config.
*/
public function get_config () return $this -> config ;
>

/**
* Create an eForm Element instance
*
* @param array $config Element config.
*/
public function __construct ( $config = [] ) $this -> set_config ( $config );
>
>

class MyElement extends Base

public static function get_definition () return [
‘type’ => ‘MyElement’ ,
];
>

public function set_config ( $config ) // Do something here
$this -> config = $config ;
>
>

$element = new MyElement ( [
‘foo’ => ‘bar’ ,
] );

print_r ( $element -> get_config () );
?>

You can see the tests being executed here and PHP 5.4 upward, the output is consistent. https://3v4l.org/8NqqW

Ok. the docs are a bit vague when it comes to an abstract class extending another abstract class. An abstract class that extends another abstract class doesn’t need to define the abstract methods from the parent class. In other words, this causes an error:

abstract class class1 <
abstract public function someFunc ();
>
abstract class class2 extends class1 <
abstract public function someFunc ();
>
?>

Error: Fatal error: Can’t inherit abstract function class1::someFunc() (previously declared abstract in class2) in /home/sneakyimp/public/chump.php on line 7

abstract class class1 <
abstract public function someFunc ();
>
abstract class class2 extends class1 <
>
?>

An abstract class that extends an abstract class can pass the buck to its child classes when it comes to implementing the abstract methods of its parent abstract class.

An interface specifies what methods a class must implement, so that anything using that class that expects it to adhere to that interface will work.

eg: I expect any $database to have ->doQuery(), so any class I assign to the database interface should implement the databaseInterface interface which forces implementation of a doQuery method.

interface dbInterface public function doQuery ();
>

class myDB implements dbInterface public function doQuery () /* implementation details here */
>
>

$myDBObj = new myDB ()-> doQuery ();
?>

An abstract class is similar except that some methods can be predefined. Ones listed as abstract will have to be defined as if the abstract class were an interface.

eg. I expect my $person to be able to ->doWalk(), most people walk fine with two feet, but some people have to hop along 🙁

interface PersonInterface () /* every person should walk, or attempt to */
public function doWalk ( $place );
/* every person should be able to age */
public function doAge ();
>

abstract class AveragePerson implements PersonInterface () private $_age = 0 ;
public function doAge () $this -> _age = $this -> _age + 1 ;
>
public function doWalk ( $place ) echo «I am going to walk to $place » . PHP_EOL ;
>
/* every person talks differently! */
abstract function talk ( $say );
>

class Joe extends AveragePerson public function talk ( $say ) echo «In an Austrailian accent, Joe says: $say » . PHP_EOL ;
>
>

class Bob extends AveragePerson public function talk ( $say ) echo «In a Canadian accent, Bob says: $say » . PHP_EOL ;
>
public function doWalk ( $place ) echo «Bob only has one leg and has to hop to $place » . PHP_EOL ;
>
>

$people [] = new Bob ();
$people [] = new Joe ();

foreach ( $people as $person ) $person -> doWalk ( ‘over there’ );
$person -> talk ( ‘PHP rules’ );
>
?>

Источник

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