为什么(对象)NULL或新的stdClass IN一个php函数? [英] why (object) NULL or new stdClass IN a php function?

查看:96
本文介绍了为什么(对象)NULL或新的stdClass IN一个php函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁可以解释为什么会返回错误:

Who can explain why this returns an error:

$test = new myclass();

class myclass {
    private $object = (object) NULL;

    public function addmember() {
        $this->object->member1 = 'member 1';
    }
}
$test -> addmember();

...这是正常的:

$test = new myclass();

class myclass {
    private $object = '';

    public function addmember() {
        $this->object = (object) NULL;// new stdClass();
        $this->object->member1 = 'member 1';
    }
}
$test -> addmember();

但是为什么?谁能解释为什么第一个例子是wroing?
为什么我必须在函数中加上(object)NULL的行?

But why? Who can explain why the first example is wroing? Why I have to put the line with "(object)NULL" IN the function?

推荐答案

php.net

From php.net:


这个声明可以包括一个初始化,但是这个
初始化必须是一个常量值 - 也就是说,它必须能够在编译时评估
,并且不能依赖于运行时

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

例如,您无法执行此操作:

For example, you can not do this:

<?php
class A {
    public $x = 1 + 2; // < expression
}
?>

但可以这样做:

<?php
class A {
    public $x;

    public function __construct(){
        $this->x = 1 + 2;
    }
}
?>

此外,您可以通过常量值在类主体中初始化属性,不需要对分析过程:

Also, you can initialize property within a class body by constant value, that does not need to be evaluated on parse process:

<?php
class A {
    public $x = 123; // < constant value
}
?>

这篇关于为什么(对象)NULL或新的stdClass IN一个php函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆