简体   繁体   English

如何在实例化对象之前将 PHP 变量定义为特定的类类型?

[英]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.我正在创建我自己的MVC框架,我希望它非常基础,但是当我使用一些IDE ,比如EclipseNetBeans他们往往会给我警告,告诉我那些变量没有初始化或者他们不认识他们的类型是,所以它们不会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 Delphi we do var Test = TTest;就像在Delphi一样,我们执行var Test = TTest; and in Java we do String testString;Java我们执行String testString; before testString = new String;testString = new String;之前testString = new String;

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;

}

PHP is loosely typed, so you can't do it like you do in Java. PHP 是松散类型的,所以你不能像在 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.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.类型声明可以添加到函数参数、返回值以及从 PHP 7.4.0 开始的类属性。

Off course not for all php versions!当然不是所有的 php 版本!

see more 查看更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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