Php type hint Can two types be allowed?

Can I resolve two different types using type hints? For instance. Parameter 1 can be either of two classes

function log (User|File $requester) {
}
+11
source share
5 answers

Academically, this is called union of types .

Type union in PHP

You can cheat by creating interfaces, parent types, etc., As mentioned in other answers, but what's the point besides adding complexity and LoC to your project? In addition, this cannot work for scalar types, since you cannot extend / implement a scalar type.

, , . , / , - , .

PHP... , . , , .

, :

/**
 * Description of what the function does.
 *
 * @param User|File $multiTypeArgument Description of the argument.
 *
 * @return string[] Description of the function return value.
 */
function myFunction($multiTypeArgument)
{

IDE . , ..

API ( PHP ..) API.

@tilz0R - :

function log($message) {
    if (!is_string($message) && !$message instanceof Message) {
        throw new \InvalidArgumentException('$message must be a string or a Message object.');
    }

    // code ...
}

PHP ()

14 2015 PHP RFC PHP 7.1. 18 "" 11 "".

RFC , PHP , (User|File).

RFC , , , , , , , (, " , "", ").

+13

PHP. interface User File, log():

<?php
interface UserFile {
}

class User implements UserFile {
}
class File implements UserFile {
}

// snip

public function log (UserFile $requester) {
}
+7

You can check the internal type function.

function log ($requester) {
    if ($requester instanceof User || $requester instanceof File) {
        //Do your job
    }
}
+3
source

You can create a parent class for these two:

abstract class Parent_class {}
class User extends Parent_class {
    // ...
}
class File extends Parent_class {
    // ...
}

And use it in function

function log (Parent_class $requester) {
    // ... code
}
+1
source

Or you can have 2 methods for each and one dynamic method:

function logUser($requester)
{
  //
}
function logFile($requester)
{
  //
}

And dynamic

function log($requester)
{
  if ($requester instanceof File) {
    return $this->logFile($requester);
  }

  if ($requester instanceof User) {
    return $this->logUser($requester);
  }

  throw new LogMethodException();
}
0
source

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


All Articles