我在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();
时,我希望变量具有默认值。有可能实现吗?
答案 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();