Home > Software design >  Declare new object instance in variable inside a class in PHP
Declare new object instance in variable inside a class in PHP

Time:01-19

Well, I will be clear, Im getting an error while declaring a variable as an instance of another class. Both class are in different files and I make a simple example of it to show quickly whats the error.

The error Im getting is the following one:

PHP message: PHP Fatal error:  New expressions are not supported in this context in Nameclassfile.php on line 6"

Im not an expert with php, currently Im running php 8.1 and Im not even sure if is allowed to declare variables as instances of other classes.

Well, my code is:

  • First Class file: Nameclassfile.php
<?php
    require_once "Valueclassfile.php";
    class NameClass {
        private $name;
        private $value = new ValueClass();

        function __construct() {
            $this->name = "Default name";
        }

        function get_name() {
            return $this->name;
        }

    }
?>
  • Second Class file: Valueclassfile.php
<?php
    class ValueClass {
        private $value;

        function __construct() {
            $this->value = "Default Value";
        }

        function get_value() {
            return $this->value;
        }
    }
?>

I hope you can bring me a hand, best regards.

CodePudding user response:

You can definitely declare variables as instances of other classes, but you can only declare static (i.e., compile-time) values for your property initializations.

class Foo {
    private $value = 123;
}

You can't use code that requires execution (i.e., run-time) like this:

class Foo {
    private $value = call_some_function();
}

Or this:

class Foo {
    private $value = new ValueClass();
}

The simple workaround is to just do your initialization in the constructor:

class NameClass {
    private $value;

    function __construct() {
        $this->value = new ValueClass();
    }
}

Note, with 8.1 you can use the constructor property promotion feature, which does allow instances of new:

class NameClass {
    function __construct(private $value = new ValueClass()) {
    }
}
  • Related