Re: PHP 4 to 5 class issues involving static methods and $this
| From: | Greg Beaver | Date: | Wed, 17 Nov 2004 23:28:21 +0000 |
| Subject: | Re: PHP 4 to 5 class issues involving static methods and $this | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-202357@lists.php.net to get a copy of this message | ||
Chris wrote:
I have a class where I need to be able to use the methods as static methods as well as using them inside an initialized class. Here's an example of what I need to do: class my_class {<?php abstract class static_my_class {var $elements = array(); // holds all of my elementsfunction format_string($string) { // format the string... return $this->elements[] = $string; }function show_all() { return implode("\n", $this->elements); }} This worked fine in PHP 4. It silently ignored the $this->elements[] assignment in statically called methods and just returned my formatted string without any fuss. However, in PHP 5, I understand that I'm now required to declare the method format_string as public static if I want to just call my_class::format_string(), and if I want to use $elements inside a static method, it also requires being declared as static. I also understand that I can't use $this inside a statically called method. I've tried these things, but they don't seem to help. How can I rewrite my class for PHP 5 to emulate the functionality I had in PHP 4 in an error free way?
public static function format_string($string) {
}
}
class my_class {
var $elements = array();
public function __call($method, $args) {
try {
$rm = new ReflectionMethod('static_my_class', $method);
return $this->elements[] = $rm->invoke(null, $args);
} catch (ReflectionException $e) {}
}
}
static_my_class::format_string('a');
$a = new my_class;
$a->format_string('a');
?>
Greg