전체 솔루션이 좋지 않지만 서로 정적 정적 메서드로 호출되는 개인 정적 메서드가있을 수 있습니다.
이것은 생성자가 아니며 일반적으로 생성자가 생성 및 객체화에 사용되며 정적 컨텍스트에 객체가 없으므로 정상입니다.
그래서, 각각의 정적 호출 후 일반적인 기능을 발사를 위해, 당신은 사용할 수 있습니다
called
method2;
에 결과
class Example {
private static function common() {
echo 'called';
}
public static function method1() {
self::common();
echo "</br> method1;";
}
public static function method2() {
self::common();
echo "</br> method2;";
}
}
Example::method2();
은 또한 정적 방법으로 개체를 구축 할 수 있습니다
class Example {
private function __construct() {
echo 'contructor called';
}
public static function method1() {
$self = new self();
echo "</br> method1;";
}
public static function method2() {
$self = new self();
echo "</br> method2;";
}
}
Example::method1();
결과 :
contructor called
method1;
여기서 문제는 각 메소드가 생성자의 새 인스턴스를 생성 할 수 있다는 것입니다.
제안 된대로 싱글 톤 패턴을 사용하여 모든 정적 메서드에서 클래스의 인스턴스를 공유 할 수 있습니다.
class Example {
private static $_inst = null;
private $_x = 0;
private function __construct() {
echo 'contructor called';
}
private static function getInstance() {
if(self::$_inst == null) {
self::$_inst = new self();
}
return self::$_inst;
}
public static function method1() {
self::getInstance();
self::getInstance()->_x = 100;
echo "</br> method1;";
}
public static function method2() {
self::getInstance();
echo self::getInstance()->_x;
echo "</br> method2;";
}
}
Example::method1();
Example::method2();
에 발생합니다 어떤 :
contructor called
method1;100
method2;
그래서 method2()
이라고합니다,하지만 당신이 볼 수있는 생성자가 두 번째로 호출되지 않을 때 저장되는 인스턴스 변수 $_x
의 값이 하나의 contructor called
있다 그 결과
그리고 나 자신을 되풀이하기 위해,이 모든 아이디어는 끔찍합니다.
예를 들어 주시겠습니까? – Speedwheelftw
@ user3540050'Example :: method1()'과 같은 정적 표기법이 더 이상 사용되지 않게되었을 때? 어떤 증거? – hindmost