开发者

php default value and non-object

开发者 https://www.devze.com 2023-01-22 04:34 出处:网络
i have a multipage form with some textfields. When you fill out the form and press next the form stores the values in an object.

i have a multipage form with some textfields. When you fill out the form and press next the form stores the values in an object. When you press the backbutton it reloads those values in textfields. This works fine.

But when you initially load the form, the object isn't created so there is nothing to load the values from and i get a Call to a member function on a non-object error.

example:

<inputfield 开发者_开发知识库value='$object->getValue()'>

is there a way to tell it that when the object doesn't exist to just leave it empty?


You could do the following before using the object:

// All methods called on this object return an empty string.
class EmptyObject {
    public function __call($name, $args) {
        return '';
    }
}

// Use fake object if $object is not defined correctly.
if (!is_object($object)) {
    $object = new EmptyObject();
}

__call is a magic method in PHP. It gets invoked every time an undefined method is called on the object.


The is also an isset method:

if(isset($object)){
     //it is there
}


Try this:

$output = "<inputfield value='". (isset($object) ? $object->getValue() : '') . "'>";


There is is_object method:

if (is_object($object)){
  // it is there
}

So you can check for it something like this:

<inputfield value='<?php is_object(@$object) ? $object->getValue() : '';?>'>
0

精彩评论

暂无评论...
验证码 换一张
取 消