H
H
htbk092020-06-12 13:48:47
PHP
htbk09, 2020-06-12 13:48:47

Why pass an instance of a class as an argument?

Can you please tell me how this action works in practice?
PS I've been learning PHP for some time now.

<?php
   
  // определяем два пустых класса
  class cat {}
  class wrong {}
   
  class write {
     
    // метод, который принимает аргументы только типа cat
    function getobj(cat $getCat) {   // определяем параметр типа cat
      echo 'Получен объект типа cat';
    }
   
  }
   
  // создаем экземпляр типа write
  $kitty = new write();
   
  // работает: передали в качестве аргумента экземпляр типа cat
  $kitty->getobj( new cat() );
  // здесь будет ошибка: передали в качестве аргумента экземпляр типа wrong
  $kitty->getobj( new wrong() );
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-06-12
@htbk09

This is just a demonstration of how argument type declarations work. Since the first argument to the getobj method is specified to be of type cat, any attempt to pass a value of any other type will result in an error.

F
FanatPHP, 2020-06-12
@FanatPHP

Forget OOP for a moment. Learn basic syntax.
Understand what the parameters are for.
After that, such questions will not arise.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question