How to prevent the use of the wrong type in PHP?

PHP, as we all know, is very poorly printed. The language does not require an indication of any type for function parameters or class variables. It can be a powerful feature.

Sometimes, although this can make debugging your script painful. For example, passing one type of object to a method that expects another type of object may result in error messages complaining that there is no specific variable / method for the transferred object. These situations are mostly annoying. More onerous problems are when you initialize one object with an object of the wrong class and that the "wrong object" will not be used to the end in the execution of the script. In this case, you will get the error much later than when you passed the original argument.

Instead of complaining that what I have passed does not have a specific method or variable, or waits much later in the execution of the script for my passed object to be used, I would rather have an error message where I indicate the object is incorrect type, complaining about the wrong or incompatible type of object.

How do you deal with these situations in your code? How do you detect incompatible types? How can I introduce some type checking in my scripts so that I can get more clear error messages?

Also, how can you do this, given accounting for inheritance in Php? Consider:

<?php
class InterfaceClass
{
#...
}

class UsesInterfaceClass
{
   function SetObject(&$obj) 
   {
       // What do I put here to make sure that $obj either
       // is of type InterfaceObject or inherits from it       

   }
}
?>

Then the user of this code implements an interface with his specific class:

<?php

class ConcreteClass extends InterfaceClass
{
}



?>

, ConcreteClass SetObject. ?

+3
7

PHP (5 +).

 <?php
 class UsesBaseClass
 {
      function SetObject(InterfaceObject $obj) 
      {
      }
 }
 ?>

, .

, "" ...

+11

hinting, , .

<?php
class MyCoolClass {
   public function passMeAnArray(array $array = array()) {
      // do something with the array  
   }  
 }  
 ?>

, , ::passMeAnArray() array, , - .

+4

is_ *:

public function Add($a, $b)
{
  if (!is_int($a) || !is_int($b))
    throw new InvalidArgumentException();
  return $a + $b;
}
+2

@ , , , .

instanceOf - , , .

+1

, . . , . .

, . , .

+1

, , script , , Y / X, , .

, , - : .

- , , , .

Pythonista...

+1

error_reporting ini php.ini error_reporting,

0

Source: https://habr.com/ru/post/1697549/


All Articles