On Sat, 03 May 2008 16:37:40 +0200, Ronald Raygun <in*****@domain.com
wrote:
If I have a function that expects first argument to be of type (class
foo) and second argument to be of type class foobar,how do I check/
ensure that I have been passed the right parameter types?
In C++, it would be done something luike this:
void Func(const foo& foo_objectRef, const foobar& foobar_objectRef)
How can I enforce the requirement that only these data types can be
passed to the function Func above?
Since PHP is loosely typed, I suspect that there is no way of enforcing
this kind of type integrity, - so in case I can't enforce this - how can
I atleast check that I have not been passed a string (for example), when
I am expecting an object of type foo or foobar?
Since PHP5 you can require a certain kind of object (or an array):
<?php
//Classes
class Foo {
function bar(Foo $foo, Foobar $foo = null){
echo "Works\n";
}
}
class Bar extends Foo{}
interface Foobar{}
class Foz implements Foobar{}
class Baz{}
//Errors to exceptions
function _error_handler($errno,$errstr){
if($errno & error_reporting()) throw new Exception($errstr);
return true;
}
set_error_handler('_error_handler');
//Illustration
$foo = new Foo();
try{$foo->bar(new Foo());}
catch (Exception $e){ echo "Doesn't work.\n";}
try{$foo->bar(new Bar());}
catch (Exception $e){ echo "Doesn't work.\n";}
try{$foo->bar(new Baz());}
catch (Exception $e){ echo "Doesn't work.\n";}
try{$foo->bar(new Foo(),new Foz());}
catch (Exception $e){ echo "Doesn't work.\n";}
try{$foo->bar(new Foo(),null);}
catch (Exception $e){ echo "Doesn't work.\n";}
try{$foo->bar(new Foo(),new Baz());}
catch (Exception $e){ echo "Doesn't work.\n";}
?>
Result:
Works
Works
Doesn't work.
Works
Works
Doesn't work.
Manual:
http://nl2.php.net/manual/en/languag...ypehinting.php
--
Rik Wasmus