Cedric
Cedric

Reputation: 5303

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

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 ?

Upvotes: 13

Views: 11870

Answers (5)

Shayan
Shayan

Reputation: 21

You can have other class objects in your current class, but you must make it in __contractor (or somewhere else) before use.

class Foo {
  private Bar $f1;
  public Bar2 $f2;
  public function __construct() {
    $f1 = new Bar();
    $f2 = new Bar2();
}}

class Bar1 {...}
class Bar2 {...}

Upvotes: 1

Gordon
Gordon

Reputation: 317217

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.

Upvotes: 15

Fidi
Fidi

Reputation: 5824

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;
    }
}

Upvotes: 0

Pekka
Pekka

Reputation: 449823

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

Upvotes: 7

Sjoerd
Sjoerd

Reputation: 75689

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

Upvotes: 2

Related Questions