Kirzilla
Kirzilla

Reputation: 16596

Restrict type of method parameter with two or more class names?

We can restrict type of method parameters; for example, we should say that function parameter should be an instance of object described in class with name "Some Class".

function some_function(Some_Class $object) {
}

Is there any php native posibilities to restrict method parameter with two or more classes? For examle, "Some Class" or "Some Class2" or "Some Class3".

Or maybe there is any way to restrict method parameter with classes which implements interface with name "Some_Interface"?

Thank you.

Upvotes: 0

Views: 577

Answers (3)

Edurne Pascual
Edurne Pascual

Reputation: 5667

In principle not, but you can fake it: since PHP is a dynamic language, type errors happen at runtime; and you can manually trigger an error by adding something like this at the start of your function:

if(check_any_type_constraints_here)
     trigger_error("Argument is not valid!", E_USER_ERROR);

In order to crash the script, it will work as reliably as PHP's built-in parameter type-checking ;).

You just need to ensure that, if you add an actual constraint on the method parameter list, all valid values will be able to go through it (you don't need to ensure all invalid values will fail the check, that's what the manual check is for). For OR'ing types, the safest way to achieve this is to not declare the type in the header, and fully rely on the manual check. If you ever want to AND types (like if you want a value that implements two or more specific interfaces), then you can put either on the header (preferably the one most likely to fail), and check the other(s) on the body.

Hope this helps.

Upvotes: 0

Gordon
Gordon

Reputation: 317029

You can do it with an interface, e.g.

interface LoggableInterface
{
    public function log($message);
}

Some classes implementing the interface

class FileLog implements LoggableInterface { 
    public function log() { /* code to log to File ... */ }
}

class DbLog implements LoggableInterface { 
    public function log() { /* code to log to Db ... */ }
}

class SysLog implements LoggableInterface { 
    public function log() { /* code to log to SysLog ... */ }
}

Then you can use it as a TypeHint like this:

function some_function(LoggableInterface $anyLogger);

This way you make sure the param passed to some_function() has a method log(). It doesn't matter which concrete you pass to it (FileLog, DbLog or SysLog), but just that these classes implement the interface.

Upvotes: 3

Ming-Tang
Ming-Tang

Reputation: 17651

You should use class inheritance or interfaces to do that.

Upvotes: 0

Related Questions