从构造函数调用varibale并在另一个函数中输出

时间:2017-05-17 08:35:05

标签: php class

我想调用我的构造函数的变量,我如何在PHP中执行此操作?

<div class="c-hero">
    <img class="c-hero__image" src="https://snag.gy/mZNKqJ.jpg">
  <div class="c-hero__item">
    <p class="c-hero__quote">quote</p>
  </div>
</div>

我的问题背景:

我有一个包含大量配置的表单。单击保存按钮后,不同的方法会创建PHP文件的不同部分。

该方法使用相同的变量。

如何将此信息发送到不同的方法?

提前多多感谢!

2 个答案:

答案 0 :(得分:1)

当您尝试定义变量以使其在类上下文中可全局调用时,您需要使用$this

function __constructor() {
    $this->temp["var_1"] = $_POST['var_1'];
    $this->temp["var_2"] = $_POST['var_2'];
}

定义属性(变量)visibility也是一种很好的做法:

public $temp = array();

function __constructor() {
    $this->temp["var_1"] = $_POST['var_1'];
    $this->temp["var_2"] = $_POST['var_2'];
}

也是为了从OOP本质中获益,你需要让你的对象是一个独立的对象,可以这么说,

将任何外包变量插入如下参数:

public $temp = array();

function __constructor($data)
{
    $this->temp["var_1"] = $data['var_1'];
    $this->temp["var_2"] = $data['var_2'];
}

答案 1 :(得分:1)

在面向对象的PHP编程中,在构造函数中使用$this。此外,您还需要声明要在构造中使用的变量。您在constructor中也有拼写错误。更改为construct

class MyClass {

    var $temp = array();//declare as array

    function __construct($postedVariables) {//pass $_POST here
        $this->temp["var_1"] = $postedVariables['var_1'];//now this variable can be used throughout this class(Filter this variable)
        $this->temp["var_2"] = $postedVariables['var_2'];//now this variable can be used throughout this class(Filter this variable)
    }

    function firstMethod() {
        echo 'output var 1 from contructor';
        echo $this->temp["var_1"];
    }

    function secMethod() {
        echo 'output var 2 from contructor';
        echo 'test2';
        echo $this->temp["var_2"];
    }

}
//call your class as:
$myCLass = new MyClass($_POST);//pass your post array
相关问题