PHP object class variable

2020-04-10 13:54发布

I have built a class in PHP and I must declare a class variable as an object. Everytime I want to declare an empty object I use:

$var=new stdClass;

But if I use it to declare a class variable as

class foo
{
    var $bar=new stdClass;
}

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

PS: I'm using PHP 4.

标签: php oop class php4
3条回答
放我归山
2楼-- · 2020-04-10 14:23

You can only declare static values this way for class members, i.e. ints, strings, bools, arrays and so on. You can't do anything that involves processing of any kind, like calling functions or creating objects.

You'll have to do it in the constructor.

Relevant manual section:

In PHP 4, only constant initializers for var variables are allowed. To initialize variables with non-constant values, you need an initialization function which is called automatically when an object is being constructed from the class. Such a function is called a constructor (see below).

查看更多
【Aperson】
3楼-- · 2020-04-10 14:26

You should not create your object here.

You should better write setter and getter

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

查看更多
等我变得足够好
4楼-- · 2020-04-10 14:27

Classes and Objects (PHP 4). A good read everytime!

查看更多
登录 后发表回答