way to specify class's type of an object in PHP

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.


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


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

Tags:

Php

Oop

Types