Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使变量的行为类似于函数_Php - Fatal编程技术网

Php 使变量的行为类似于函数

Php 使变量的行为类似于函数,php,Php,我正在制作一个使用多项式和单项式的PHP脚本(单项式的一个例子是42xk^2c^3d)。单项类定义如下: class Monomial { public $coefficient; // i.e. 42 public $letters; // an array of Letter objects public $literal; // i.e. xk^2c^3d /* Code */ } 现在,在我的应用程序中,我同时使用字母数组和文字变量。我不

我正在制作一个使用多项式和单项式的PHP脚本(单项式的一个例子是
42xk^2c^3d
)。
单项
类定义如下:

class Monomial {
    public $coefficient; // i.e. 42
    public $letters;     // an array of Letter objects
    public $literal;     // i.e. xk^2c^3d
    /* Code */
}

现在,在我的应用程序中,我同时使用字母数组和文字变量。我不想在更新单项式时(例如,在向其添加内容时)手动更新
literal
变量:相反,我希望它是动态的,以便访问它时调用函数“构建”它。有什么想法吗?

编写一个函数
setlets
(甚至是
updatemonical
),它更新变量并使用它,而不是直接访问变量。一般来说,最好不要公开类成员。

使用
\uu get
方法。例如:

class Monomial {
    public $coefficient;
    public $letters;
    public $literal;

    function __get($var) {
        if ($var != "literal") {
            return $this->data[$var];
        } else {
            foreach ($this->letters as $letter) {
                $return.=$letter->literal;
            }
            return $return;
        }
}

字母
对象中会有一个类似的
\uuuu get
方法,它会根据请求生成文本字符串。

检查此选项是的,php
\uu get
\uu set
中的神奇方法应该适合您。