将静态变量设置为函数php类



我想将静态变量的值设置为函数。但是__construct从不使用静态调用运行。那么,我可以做什么来设置这个变量,这样我就可以在课堂上多次重复使用它呢?

function sayhey(){
return 'hey';   
};
// my class i do control
class Class1 {
private static $myvar;

public function __construct(){
self::$myvar = sayhey();
}

public static function func1(){
echo '<pre>'; print_r(self::$myvar); echo '</pre>';
}
}// end class
// how can i make this work if the __construct never runs for static calls?
Class1::func1();
// obviously this works
//$class1 = new Class1();
//$class1->func1();

试试这个

<?php
function sayhey(){
return 'hey';   
};
// my class i do control
class Class1 {
private static $myvar;

public function __construct(){
self::$myvar = sayhey();
//echo '<pre>11 '; print_r(self::$get_cart_contents); echo '</pre>';
}

public static function func1(){
echo '<pre>'; 
self::$myvar = self::$myvar ?? sayhey(); 
print_r ( self::$myvar );
echo '</pre>';
}
}// end class
Class1::func1();

您需要在某个时刻初始化静态属性。由于构造函数对静态方法没有用处,因此它"替换"了通过创建init()方法(也是静态方法(所完成的工作,该方法在self::$myvar为null时调用(使用self::$myvar ?? self::init()

function sayhey(){
return 'hey';
};
// my class i do control
class Class1 {

private static $myvar;

public static function init(){
self::$myvar = sayhey();
return self::$myvar;
}

public static function func1(){
echo '<pre>'; print_r(self::$myvar ?? self::init()); echo '</pre>';
}

}// end class
// how can i make this work if the __construct never runs for static calls?
Class1::func1();

您还可以将函数名保存在变量中,而不是调用的结果。

function sayhey(){
return 'hey';   
};
class Class1 {
private static $myvar;

public static function set($fct){
self::$myvar = $fct;
}

public static function func(){
$result = (self::$myvar)();
return $result;
}
}
Class1::set('sayhey');
echo Class1::func();  //hey

我怀疑特质更好。

trait myfunctions{
public static function sayhey(){
return 'hey';   
}
}
class Class1 {
use myfunctions;
}
class Class2 {
use myfunctions;
public static function fct1(){
return self::sayhey();
}
}
echo Class1::sayhey();  //hey
echo Class2::sayhey();  //hey
echo Class2::fct1();  //hey

最新更新