PHP object class variable

I created a class in PHP and I have to declare the class variable as an object. Every time I want to declare an empty object that I use:

$var=new stdClass;

But if I use it to declare a class variable as

class foo
{
    var $bar=new stdClass;
}

a parsing error occurs. Is there a way to do this or should I declare a class variable as an object in the constructor function?

PS: I am using PHP 4.

+3
source share
3 answers

You can declare static values ​​only for class members, i.e. ints, strings, bools, arrays, Etc. You cannot do anything related to processing of any type, for example, calling functions or creating objects.

.

:

PHP 4 var. , , , . (. ).

+5
+2

You should not create your object here.

Better to write setter and recipient

<?php
    class foo
    {
       var $bar = null;

       function foo($object = null)
       {
          $this->setBar($object);
       }

       function setBar($object = null)
       { 
          if (null === $object)
          {
             $this->bar = new stdClass();
             return $this;
          }

          $this->bar = $object;
          return $this;
       }
    }

By the way, you should use PHP5 to work with OOP, which is more flexible ...

+2
source

Source: https://habr.com/ru/post/1716763/


All Articles