PHP Value Object automatically creates

Suppose I have a class object defined in php where each variable in the class is defined. Sort of:

class UserVO {
  public $id;
  public $name;
}

Now I have a function in another class that expects an array ($ data).

function save_user($data) {
//run code to save the user
}

How to tell php that the parameter $ data should be entered as UserVO? Then I could complete the code to do something like:

$something = $data->id; //typed as UserVO.id
$else = $data->name; //typed as UserVO.name

I am assuming something like the following, but this clearly does not work

$my_var = $data as new userVO();
+3
source share
2 answers

Use hint type or instanceof .

hint type

public function save_user(UserVO $data);

Throws an error if this type is not an instance of UserVO.

InstanceOf

public function save_user($data)
{
    if ($data instanceof UserVO)
    {
        // do something
    } else {
       throw new InvalidArgumentException('$data is not a UserVO instance');
    }
}

InvalidArgumentException ( salathe , ), .

,

+7

PHP5 . .

function save_user(UserVO  $data) {
//run code to save the user
}

http://php.net/manual/en/language.oop5.typehinting.php

+3

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


All Articles