Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a PHP variable as a specific class type before instantiate an object?

Tags:

types

php

I am creating my own MVC framework, and I want it to be very basic, but when I use some IDE's like Eclipse or NetBeans they tend to give me warnings telling that those variables where not initialized or they do not recognize what type they are, so they do not autocomplete the class methods or properties the variable supposed to be of.

To override this, I created a PHP file where the the global environment variable is set and a new object is instantiated and then destroyed, so the IDE recognizes it and I can work with it well.

But then these classes constructors execute at that time, and it could be dangerous and even slow down my code. So, to override this better, how could I define a variable type to be of a specific class, without instantiate it?

Like in Delphi we do var Test = TTest; and in Java we do String testString; before testString = new String;

like image 636
NaN Avatar asked Nov 26 '13 16:11

NaN


People also ask

How do you declare a class variable in PHP?

The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.

What is the correct way of initiating a PHP class?

class ¶ Basic class definitions begin with the keyword class , followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP reserved word.

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.


1 Answers

Depending on the IDE, you can use PHPDoc comments to get code completion

 /** @var YourClass */
 private $variable;

This is IDE specific though

Edit and 6 years later (almost to the day), with the advent of php 7.4, you can now declare types for class properties:

Class SomeClass
{

    private YourClass $variable;

    public string $something_else;

}
like image 81
Steve Avatar answered Oct 23 '22 19:10

Steve