PHP object class variable

荒凉一梦 提交于 2019-12-01 20:30:45

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

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!