简体   繁体   中英

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

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;

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;

}

PHP is loosely typed, so you can't do it like you do in Java. You can provide type hinting for custom classes, though. See this description on PHP.net: http://php.net/manual/en/language.oop5.typehinting.php

我现在知道 Facebook 开发人员创建了一个名为Hack的 PHP 变体,这是一个具有强类型的 PHP。

Type declarations can be added to function arguments, return values, and, as of PHP 7.4.0, class properties.

Off course not for all php versions!

see more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM