Home » Php » class – How do I Use Inner Classes in PHP?

class – How do I Use Inner Classes in PHP?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m from a Java background, and I want to use an inner class in php. Every time I put the inner class though, I get a syntax error. Is this possible with PHP? Also, how do I reference the outer class? Do I get access to ALL its data members?

<?php

class OuterClass {
    var $x = 15;
    function __construct() {

    }

    class InnerClass {                  // error when InnerClass is static
        function __construct() {        // error when InnerClass is static
            echo $x;
        }
    }
}

?>

This is used for a MoveClass (as in make a move) of a specific card game. I think it’d be good design to put these classes together because they don’t make sense apart. Also, the MoveClass needs to know about some data members of the Game class. Why not make it a function? It’s simply too big.

Edit:

What about nested classes? From what I understand, those have to be static? O_o

How to&Answers:

PHP does not allow for inner classes. Should you wish to access all of the data members from the parent class, I would suggest you employ Inheritance.

A possible alternative:

class OuterClass {
    var $x = 15;
    function __construct() {

    }
}
class ChildClass extends OuterClass {
    function __construct() {
        parent::__construct();
    }
}

You can envoke a method form the parent class by referring to the class itself; In PHP you can do this with the parent keyword. So, to refer to a method in the context of a class rather than an object we use :: as opposed to ->.

Answer:

in PHP 5.4 or later, you can use PHP Traits which are designed more for multiple inheritance, but may suit your needs. From the PHP Documentation:

A Trait is similar to a class, but only intended to group
functionality in a fine-grained and consistent way. It is not possible
to instantiate a Trait on its own. It is an addition to traditional
inheritance and enables horizontal composition of behavior; that is,
the application of class members without requiring inheritance.

http://php.net/manual/en/language.oop5.traits.php

Answer:

As mentioned in comments to this answer from another question, the PHP version of this functionality has been added in PHP 7. It does not seem to provide exactly what you are asking for. However, it should provide you a similar design pattern.

Here’s the RFC describing how it works: https://wiki.php.net/rfc/anonymous_classes

As mentioned in the other answer’s comments, search the RFC page for “nested” to see an example of nesting inside an outer class.

Answer:

You might want to use a stdClass instead. Here’s an SO question about it: What is stdClass in PHP?

Answer:

You can’t nest classes like that.

Look at the “extends” section of the manual.