Re: PHP 4 to 5 class issues involving static methods and $this

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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 {
    var $elements = array(); // holds all of my elements

    function 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?

<?php abstract class static_my_class { 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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux