tags:

views:

38

answers:

4

Is there a way to specify an object's attribute's type in PHP ? for example, I'd have something like :

class foo{
 public bar $megacool;//this is a 'bar' object
 public bar2 $megasupercool;//this is a 'bar2' object
}


class bar{...}
class bar2{...}

If not, do you know if it will be possible in one of PHP's future version, one day ?

+1  A: 

No. You can use type hinting for function parameters, but you can not declare the type of a variable or class attribute.

Sjoerd
+2  A: 

What you are looking for is called Type Hinting and is partly available since PHP 5 / 5.1 in function declarations, but not the way you want to use it in a class definition.

This works:

<?php
class MyClass
{
   public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }

but this doesn't:

class MyClass
  {
    public OtherClass $otherclass;

I don't think this is planned for the future, at least I'm not aware of it being planned for PHP 6.

you could, however, enforce your own type checking rules using getter and setter functions in your object. It's not going to be as elegeant as OtherClass $otherclass, though.

PHP Manual on Type Hinting

Pekka
It should be noted that TypeHinting is not available (yet) for Scalar Types.
Gordon
@Gordon: That's right. But of course you could just check for a specific type in an short if-condition within the method. And if it is not satisfied, by the given parameter you throw an exception.
faileN
@faileN yes, something like [is_scalar()](http://de3.php.net/manual/en/function.is-scalar.php) or any of the specific is_* functions.
Gordon
A: 

You can specify the object-type, while injecting the object into the var via type-hint in the parameter of a setter-method. Like this:

class foo
{
    public bar $megacol;
    public bar2 $megasupercol;

    function setMegacol(bar $megacol) // Here you make sure, that this must be an object of type "bar"
    {
        $this->megacol = $megacol;
    }

    function setMegacol(bar2 $megasupercol) // Here you make sure, that this must be an object of type "bar2"
    {
        $this->megasupercol = $megasupercol;
    }
}
faileN
I didn't know it was possible to overload a method that way. Nice.
Cedric
+2  A: 

In addition to the TypeHinting already mentioned, you can document the property, e.g.

class FileFinder
{
    /**
     * The Query to run against the FileSystem
     * @var \FileFinder\FileQuery;
     */
    protected $_query;

    /**
     * Contains the result of the FileQuery
     * @var Array
     */
    protected $_result;

 // ... more code

The @var annotation would help some IDEs in providing Code Assistance.

Gordon
Nice alternative, perfect for documentation purposes.
Pekka