PHP 中类的默认可见性是多少? [英] What's the visibility of a class by default in PHP?

查看:29
本文介绍了PHP 中类的默认可见性是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 中找到属性和方法的默认可见性PHP 手册.但我找不到关于课程本身的任何信息.

I could find the default visibility of a property and a method in the PHP manual. But i couldn't find any info regarding the class itself.

我猜它是公开的.但如果有人可以链接到手册中写的部分,我将不胜感激.

My guess is that it's public. But if someone could link to the part where this is written in the manual i would appreciate it.

推荐答案

Simply Put

公开.PHP 不支持公共类以外的任何东西.

Simply Put

Public. PHP doesn't support anything other than public classes.

与 Java/.NET/etc 不同,没有任何包、程序集、内部或嵌套类的概念.命名空间本质上只是避免 IncredablyLongClassNames 的语法糖,并且不能对可见性提供任何实际更改.

Unlike Java/.NET/etc, there isn't any concept of packages, assemblies, internal or nested classes. Namespaces are essentially just syntactic sugar to avoid IncrediblyLongClassNames, and can't provide any actual changes to visibility.

整个想法在非编译语言中意义不大,因为无论您使用什么范围,任何人仍然可以直接使用您的类并公开声明它.

The entire idea makes much less sense in a non-compiled language, since regardless of what scope you use, anyone could still just take your class and declare it in public.

PHP 7 引入了匿名类* 的概念,允许-the-fly 类定义.作为一个非常基本的例子:

PHP 7 introduced the concept of anonymous classes*, allowing on-the-fly class definitions. As a very basic example:

<?php
$foo = new class {
    public function hello($what)
    {
        echo 'Hello ', $what, PHP_EOL;
    }
};

(new $foo)->hello('world');

# Hello world

因为这些可以分配给变量,所以它们可以被限制在该变量的范围内,并像其他任何东西一样传递.

Because these can be assigned to variables, they can be limited to the scope of that variable, and passed around like any other.

与大多数允许匿名类的语言不同,在 PHP 中,它们从定义它们的范围继承任何东西.链接文档提供了一些如何解决此问题的示例,方法是将匿名类定义为从父类继承或传入构造函数参数.

Unlike most language that allow anonymous classes, in PHP they do not inherit anything from the scope in which they are defined. The linked documentation has some examples of how to work around this, by defining the anonymous class as inheriting from a parent or passing in constructor arguments.

*严格来说,在幕后他们确实有名字,因此如果有人可以在实例上运行 get_class() 那么他们就可以实例化他们自己的副本,因为 它们不会被垃圾收集.

*Strictly speaking, under the hood they do have names, and as such if someone can run get_class() on an instance then they can then instantiate their own copy, since they aren't garbage collected.

这篇关于PHP 中类的默认可见性是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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