Currently it is not possible to define types, because PHP usually accepts any type, but adding the prefix Object
to the argument, you are not properly declaring the type for this argument, you are declaring the instance to which that object must belong.
<?php
class Teste
{
public function show(Object $arg)
{
return $arg;
}
}
class Object {}
$objecto = (object) 'Teste';
// $objecto = new stdClass();
$teste = new Teste();
var_dump($teste->show(new Object)); # funciona (instancia de Object)
var_dump($teste->show($objecto)); # não funciona (instancia de stdClass)
?>
To solve this, just do not assign a prefix to the argument in question, and everything will work fine.
<?php
...
public function show($arg)
{
return $arg;
}
...
?>
But if you really want to define a specific type for that argument, or a requirement for that particular argument, then you must work on that argument to create that rule.
Another example would be this:
<?php
class Teste
{
public function show($object=null)
{
if(!empty($object) && gettype($object) === 'object'){
if(!($object instanceof stdClass)){
return "Retorno: \"{$object}\" é um objecto <br/>";
}
throw new Exception('é um objecto, mas não pode ser retornado como string');
}
throw new Exception("\"{$object}\" é " . gettype($object));
}
}
class Object
{
protected $nome;
public function __construct($nome=null){
$this->nome = $nome;
}
public function __toString(){
if(!empty($this->nome)){
return $this->nome;
}
return 'default';
}
}
$teste = new Teste();
try{
// print $teste->show(new stdClass());
print $teste->show(new Object('LMAO'));
// print $teste->show(new Object());
// print $teste->show(1);
// print $teste->show('teste');
// print $teste->show(0.01);
} catch (Exception $e){
print 'Excepção: ' . $e->getMessage();
}
?>
It simply throws an exception if the instance is not an object, or if it is an instance of stdClass
.
You can now pass arguments by reference, and also specify return types for functions, if you want to know more, you can follow this link and browse the "Funcions" and "Classes and Objects" categories . Of course, if you look even more, you can still find other good suggestions, there is no shortage.