سؤال

How to make this backwards compatible with PHP5.2? It works on 5.3 and later

error

Fatal error: Cannot call method self::utf8_dec() or method does not exist

code

private function utf8_decode($arr){
    array_walk_recursive($arr, 'self::utf8_dec'); // <----- error

    return $arr;
}

private function utf8_dec(&$value, $key){
    $value = utf8_decode($value);
}
هل كانت مفيدة؟

المحلول 2

Instead of self, you can use the name of the class directly. It's not as flexible but it should work.

static private function utf8_decode($arr){
    array_walk_recursive($arr, 'YourClass::utf8_dec');

    return $arr;
}

static private function utf8_dec(&$value, $key){
    $value = utf8_decode($value);
}

Also you need to prefix the methods with the static keyword.

نصائح أخرى

Try this instead:

array_walk_recursive($arr, array(__CLASS__, 'utf8_dec'));

And I'd also do this:

private static function utf8_dec(&$value, $key) { // now is static!
    $value = utf8_decode($value);
}

I'd also recommend giving a look about how to define callbacks in PHP: http://php.net/manual/en/language.types.callable.php

It does not seem to be problem on type (static), rather than it is called out of scope. If you do not use strict mode it should work without you saying function is static.

<?php
class test {
    public function __construct($arr) {
        print_r(self::utf8_decode($arr));
        print_r($this->utf8_decode($arr));

        print_r(self::utf8_decode_v2($arr));
        print_r($this->utf8_decode_v2($arr));
    }
    private static function utf8_decode($arr){
        array_walk_recursive($arr, 'self::utf8_dec'); 
        return $arr;
    }
    private function utf8_decode_v2($arr){
        array_walk_recursive($arr, array($this, 'utf8_dec')); 
        return $arr;
    }


    private function utf8_dec(&$value, $key){
        $value = utf8_decode($value);
    }
}
$a = new test(array('apple','pinaple','nut'));
?>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top