如何纠正此功能中的缺陷

How to correct the Flaw in this function

 class MyClass {
  private $_callingscript; 
             public   function __construct(){
    $this->_callingscript= basename($_SERVER['SCRIPT_NAME']);
        }
        public static function Setvalue($k,$v){
   if (!empty($k)) {
   $_SESSION[$this->_callingscript.'_'.$k]= $v;//This doesnot work 
   $_SESSION[$_SERVER['SCRIPT_NAME'].'_'.$k]=$v //This works 

  }
        }
 }

 MyClass::setValue('Somename',"Somevalue");

When i call this it is giving me error "Using $this when not in object context in". How to correct the callingscript variable .Is this due to private declaration of that variable

You need to refactor your code so that you either:

  • make Setvalue a non-static function and instantiate the class:

    $mc = new MyClass();
    $mc->setValue('Somename', 'Somevalue'");
    

or

  • change _callingscript so that it is not populated through instantiation and can therefore be accessed statically via self::_callingscript

No, it's because $this doesn't get populated for static methods. Remove the static qualifier.

$this can't be accessed from within static methods. I would recommend replacing the line that dosent work to:

$_SESSION[self::_callingscript. "_" .$k] = $v;

EDIT: come to think about it, this will not work.


Attempt #2: I gave you bad information. I did forget that calling the static method would not call the __construct() method. What I do is just use non static methods...

class MyClass {

  private $_callingscript; 

  public function __construct()
  {
    $this->_callingscript = basename($_SERVER['SCRIPT_NAME']);
  }


  public function setValue($k, $v)
  {
    if (!empty($k)) {
      $_SESSION[$this->_callingscript. "_" .$k] = $v;
    }
  }

}


$MyClass = new MyClass();

$MyClass->setValue('Somename', "Somevalue");

Sorry for confusion.

You could use:

class MyClass { 
    public static function Setvalue($k, $v) { 
        static $callingScript = null;

        if($callingScript == null) {
            $callingScript = basename($_SERVER['SCRIPT_NAME']);
        }

        if (!empty($k)) {
            $_SESSION[$callingScript . '_'.$k]= $v;
        }
    }
}

or if the callingScript variable needs to be shared among other methods:

class MyClass {
    private static $callingScript = null;

    private static function getCallingScript() {
        if(self::$callingScript == null) {
            self::$callingScript = basename($_SERVER['SCRIPT_NAME']);
        }

        return self::$callingScript;
    }

    public static function Setvalue($k, $v) { 
        if (!empty($k)) {
            $_SESSION[self::getCallingScript() . '_'.$k]= $v;
        }
    }
}

As others have pointed out, $this is not accessible within static methods and if you call a static method the __construct function is not being triggered.