Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the visibility of a class by default in 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.

like image 812
Jo Smo Avatar asked Jul 19 '16 10:07

Jo Smo


1 Answers

Simply Put

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

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.

A PHP 7 Proviso: Anonymous Classes

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.

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.

*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.

like image 68
iainn Avatar answered Sep 28 '22 02:09

iainn