Currently it is not possible to define types, because the PHP standard accepts any type, but adding the prefix Object
to the argument, you’re not exactly declaring the type for that argument, you’re declaring the instance to which that object should 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 don’t give a prefix to the argument in question, and everything will work out just 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, you should then work on that argument in order 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 shall simply make an exception where the panel is not an object, or where it is a stdClass
.
Currently it is possible to pass arguments by reference, and also specify types of returns for functions, if you want to know more, you can follow this link and browse through the categories "Funcions" and "Clases and Objects". Of course, if you look further, you can still find other good suggestions, there’s plenty.
Have you tried using an abstract class encapsulating the other ones? Or do you really need to be any kind of object (including PHP’s own classes)?
– KaduAmaral
Not necessarily the PHP classes themselves, because I didn’t analyze at this point, only the classes I created myself.
– LeoFelipe