Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php inner classes support

Tags:

php

Does PHP versions 5.3 or after support inner classes? example:

class MyClass{
    class PrivateClass1{

    }
    class PrivateClass2{

    }
    class PrivateClass3{

    }

    private $obj1;
    private $obj2;
    private $obj3;

    __construct(){
        $obj1 = new PrivateClass1();
        $obj2 = new PrivateClass2();
        $obj3 = new PrivateClass3();
    }
}
like image 558
Johntor Avatar asked May 20 '12 18:05

Johntor


People also ask

What is inner class in PHP?

In object-oriented programming (OOP), an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass. – Wikipedia. So basically inner class is a class that is declared inside the scope of another class.

Does PHP support anonymous classes?

In PHP, an anonymous class is a useful way to implement a class without defining it. These are available from PHP 5.3 onwards.

Can classes be nested in PHP?

Can classes be nested in PHP? Compelling reasons for using nested classes include the following: It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.

When Should inner classes be used?

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.


2 Answers

PHP currently (5.4.3) does not support Inner/Friend Classes

And there is also no RFC in the wiki asking for addition of a feature like this.

like image 138
Gordon Avatar answered Sep 22 '22 02:09

Gordon


It's possible to create a class within another class definiton, but it's not possible to define a class within a class definition. So this means your construction in invalid.

But, you can always extend a class with another class, check this URL for more:

http://php.net/manual/en/keyword.extends.php

Check Can I instantiate a PHP class inside another class? for even more.

like image 37
Sliq Avatar answered Sep 22 '22 02:09

Sliq