먼저 변수를 다시 인스턴스화하면 설정 한 변수가 파괴되지 않습니다. 이것은 캡슐화라고하는 것으로, 클래스의 모든 인스턴스에는 OOP에있어 중요한 속성 집합이 있습니다. 값이 각 인스턴스화의 기본 클래스 정의에서 복사되는 것과 같이 기본값을 얻는다는 의미입니다. 클래스의 모든 인스턴스에서 변수를 사용할 수있게하려면 정적 변수를 사용해야합니다.
<?php
class globalVars{
private static $final = "Default Foo </br>";
private $instance = "Some default value";
public function setStatic($param){
self::$final = $param;
}
public function setInstance($param){
$this->instance = $param;
}
public function getStatic(){
return self::$final;
}
public function getInstance(){
return $this->instance;
}
}
$test = new globalVars();
$test->setStatic("Foo");
$test->setInstance("Bar");
$test2 = new globalVars();
$final = $test2->getStatic();
$instance = $test2->getInstance();
echo $final;
//outputs "Foo"
echo $instance;
//outputs the default value for the instance property because in this
//instance the value was never changed.
echo $test->getInstance();
//outputs "Bar" because the instance property was changed in this instance.
편집 : 정적 및 인스턴스 속성 간의 차이점을 표시하기 위해 클래스를 조금 변경했습니다.
왜 정적 var를 사용하지 않습니까? – Cooper