简体   繁体   中英

Setting a static variable to a function php class

I'd like to set the value of my static variable to a function. But the __construct never runs with static calls. So what's an alternate route I can do to set this variable so I can re-use it many times in my class?

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();

You need at some point to initialise the static property. As the constructor is useless for static methods, this 'replaces' the work done by creating an init() method (also static) which is called when self::$myvar is null (using 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();

Try this

<?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();

You can also save the function name in the variable instead of the result of the call.

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

I suspect traits are better.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM