I'm working on a class which needs to be accessible via static function calls as well as object methods. One thing I have found is that I'm duplicating logic across multiple functions.
Simplified example:
class Configurable{
protected $configurations = array();
protected static $static_configurations = array();
public function configure($name, $value){
// ...lots of validation logic...
$this->configurations[$name] = $value;
}
public static function static_configure($name, $value){
// ...lots of validation logic (repeated)...
self::$static_configurations[$name] = $value;
}
}
I've found a solution to this, but it feels really dirty:
class Configurable{
protected $configurations = array();
protected static $static_configurations = array();
public function configure($name, $value){
// ...lots of validation logic...
if (isset($this)){
$this->configurations[$name] = $value;
}
else{
self::$static_configurations[$name] = $value;
}
}
}
I need the static function as well so that I can set configurations throughout the application. Also, the nice thing with this technique is that I can use the same method names in both scopes.
Are there any problems with testing scope like this? Performance issues, forward compatibility issues, etc. It all works for me on PHP 5.2, and I don't need to support <5.
Definition and Usage. The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
Short Answer. Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.
The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.
The issue with the second method is that it will result in an error when error reporting is set to E_STRICT
. For example:
Strict standards: Non-static method Foo::bar() should not be called statically in /home/yacoby/dev/php/test.php on line 10
A point with PHP6 is that the E_STRICT errors are moved to E_ALL. In other words E_ALL will cover all errors including not allowing you to call non static methods statically.
An alternative method may be to move the validation logic to a static function. That way the non static function and the static function can call the validation logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With