仅在函数内部更改变量值

时间:2017-02-17 10:57:34

标签: php

我在PHP中有这个代码:

$name

所以,基本上我需要的是每次调用函数$access时保持var checkData()function functionToCheckData() { $class = new PhpClass(); $param = [ 'name' => 'Another name', 'access' => 'Another access' ]; $class->checkData($param); //$name and $access should be "another name" and "another access" $class->checkData(); //$name and $access should be "test name" and "test access" } 始终具有默认值,但只更改它{s}通过params时该函数中的值。

例如,如果调用这样的函数:

checkData()

每当我调用函数long startTime = Calendar.getInstance().getTimeInMillis(); 时,我希望变量具有默认值。有可能实现吗?

2 个答案:

答案 0 :(得分:1)

您此处未使用static。阅读静态here

您需要做什么:

class PhpClass {
    private $name   = 'Test name';
    private $access = 'Test access';

    public static function checkData($param=NULL) {
        if ( $param ) {
            $this->name   = $param['name'];
            $this->access = $param['access'];
        } else {
            $this->name   = 'Test name';
            $this->access = 'Test access';
        }

        //Rest of the function
    }
}

答案 1 :(得分:0)

您正在使用相同的对象。所以它会覆盖它。

试试这个:

<?php
   class PhpClass {
    private $name   = 'Test name';
    private $access = 'Test access';

    public  function checkData($param=NULL) {
        if ( $param ) {
            $this->name   = $param['name'];
            $this->access = $param['access'];
        } 
        echo $this->name."<br>";
        //Rest of the function
    }
}
function functionToCheckData() {
    $class = new PhpClass();

    $param = [
        'name' => 'Another name',
        'access' => 'Another access'
    ];

    $class->checkData($param); //$name and $access should be "another name" and "another access"
     $class1 = new PhpClass();
    $class1->checkData(); //$name and $access should be "test name" and "test access"
}
functionToCheckData();