如何在实例化对象之前将 PHP 变量定义为特定的类类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20222365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a PHP variable as a specific class type before instantiate an object?
提问by Please_Dont_Bully_Me_SO_Lords
I am creating my own MVCframework, and I want it to be very basic, but when I use some IDE's like Eclipseor NetBeansthey 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 autocompletethe class methods or properties the variable supposed to be of.
我正在创建我自己的MVC框架,我希望它非常基础,但是当我使用 some IDE' likeEclipse或者NetBeans他们倾向于给我警告,告诉我那些变量没有初始化或者他们不认识他们是什么类型,所以他们不要autocomplete使用变量应该属于的类方法或属性。
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.
为了覆盖它,我创建了一个 PHP 文件,其中设置了全局环境变量并实例化了一个新对象,然后销毁了它,因此 IDE 可以识别它并且我可以很好地使用它。
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 Delphiwe do var Test = TTest;and in Javawe do String testString;before testString = new String;
就像在Delphi我们所做的var Test = TTest;和Java我们String testString;之前所做的一样testString = new String;
回答by Steve
Depending on the IDE, you can use PHPDoc comments to get code completion
根据 IDE,您可以使用 PHPDoc 注释来完成代码
/** @var YourClass */
private $variable;
This is IDE specific though
虽然这是特定于 IDE 的
Edit and 6 years later (almost to the day), with the advent of php 7.4, you can now declare types for class properties:
编辑和 6 年后(几乎到今天),随着 php 7.4 的出现,您现在可以为类属性声明类型:
Class SomeClass
{
private YourClass $variable;
public string $something_else;
}
回答by jameslafferty
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
PHP 是松散类型的,所以你不能像在 Java 中那样做。不过,您可以为自定义类提供类型提示。请参阅 PHP.net 上的此说明:http: //php.net/manual/en/language.oop5.typehinting.php

