Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Value Object auto create

Tags:

object

php

Assume that I have a class value object defined in php, where each variable in the class is defined. Something like:

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

I now have a function in another class, which is expecting an array ($data).

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

How do I tell php that the $data parameter should be typed as a UserVO? I could then have code completion to do something like:

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

I'm guessing something like the following, but this obviously doesnt work

$my_var = $data as new userVO();
like image 592
JonoB Avatar asked Jan 19 '26 01:01

JonoB


2 Answers

Use type hint or instanceof operator.

type hinting

public function save_user(UserVO $data);

Will throw an error if the given type is not an instanceof UserVO.

instanceof

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

Will throw an InvalidArgumentException (thanks to salathe for pointing me out to this more verbose exception) which you will be able to catch and work with.

By the way, take a look to duck typing

like image 190
Boris Guéry Avatar answered Jan 20 '26 16:01

Boris Guéry


in PHP5 this will work. It's called a type hint.

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

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

like image 41
Palantir Avatar answered Jan 20 '26 15:01

Palantir