:: 和 -> 之间的区别在 PHP 中 [英] Difference between :: and -> in PHP

查看:49
本文介绍了:: 和 -> 之间的区别在 PHP 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是看到人们在严肃的项目中使用 :: 无处不在,-> 只是偶尔在本地环境中使用.

I always see people in serious projects use :: everywhere, and -> only occasionally in local environment.

我只使用 -> 自己,并且永远不会遇到需要类之外的静态值的情况.我是坏人吗?

I only use -> myself and never end up in situations when I need a static value outside of a class. Am I a bad person?

据我所知,-> 不起作用的唯一情况是当我尝试以下操作时:

As I understand, the only situation when -> won't work is when I try following:

class StaticDemo {  
    private static $static  
}

$staticDemo = new StaticDemo( );

$staticDemo->static; // wrong  
$staticDemo::static; // right

但是当我不通过 :: 调用简单的公共方法时,我是否错过了一些编程的正确性?

But am I missing out on some programming correctness when I don't call simple public methods by :: ?

或者只是为了在不创建实例的情况下调用方法?

Or is it just so that I can call a method without creating an instance?

推荐答案

:: 用于引用类的静态属性或方法.-> 用于引用实例属性和方法.你不会错过任何编程的正确性,如果你是一个坏人,那不是因为这个.您使用哪一个取决于您的课程目的及其编写方式.而且,PHP 直到最近才具有命名空间,因此许多人将他们的代码封装在静态类中以模拟命名空间以避免命名冲突.您可能正在看到执行此操作的代码.

:: is for referencing static properties or methods of a class. -> is for referencing instance properties and methods. You aren't missing out on any programming correctness, and if you are a bad person then it isn't because of this. Which one you use depends on the purpose of your class and how its written. But also, PHP didn't have namespaces until very recently so many people encapsulated their code in static classes to emulate namespaces to avoid naming collisions. It is possible you are seeing code that does that.

这篇关于:: 和 -> 之间的区别在 PHP 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆