Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

oop

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 ?

like image 255
Cedric Avatar asked Jul 02 '10 10:07

Cedric


People also ask

How do you call a class object in PHP?

PHP: Class Constants When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

What is a class how do you create a class and define object in PHP?

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword.

How define a class property in PHP?

Classes can have variables within it. Those variables are called properties. A property is a normal PHP variable which is in any data type (integer, string, array, object, etc). In classes, before declaring a variable, we should add the visibility keyword to define where the variable is available.


1 Answers

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.

like image 172
Gordon Avatar answered Sep 17 '22 22:09

Gordon