Non-static method ?

sunyang

Мастер
Регистрация
25 Апр 2009
Сообщения
440
Реакции
30
Пытаюсь перевести гугловским классом текст. Переводит, но выдает ошибки Non-static method:

Класс:

PHP:
<?
// GOOGLE TLANSLATE
class Google_Translate_API {

        /**
         * Translate a piece of text with the Google Translate API
         * @return String
         * @param $text String
         * @param $from String[optional] Original language of $text. An empty String will let google decide the language of origin
         * @param $to String[optional] Language to translate $text to
         */
        function translate($text, $from = '', $to = 'en') {
                $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.rawurlencode($text).'&langpair='.rawurlencode($from.'|'.$to);
                $response = file_get_contents(
                        $url,
                        null,
                        stream_context_create(
                                array(
                                        'http'=>array(
                                                'method'=>"GET",
                                                'header'=>"Referer: http://".$_SERVER['HTTP_HOST']."/\r\n"
                                        )
                                )
                        )
                );
                if (preg_match("/{\"translatedText\":\"([^\"]+)\"/i", $response, $matches)) {
                        return @self::_unescapeUTF8EscapeSeq($matches[1]);
                }
                return false;
        }
        
        /**
         * Convert UTF-8 Escape sequences in a string to UTF-8 Bytes. Old version.
         * @return UTF-8 String
         * @param $str String
         */
        function __unescapeUTF8EscapeSeq($str) {
                return preg_replace_callback("/\\\u([0-9a-f]{4})/i", create_function('$matches', 'return html_entity_decode(\'&#x\'.$matches[1].\';\', ENT_NOQUOTES, \'UTF-8\');'), $str);
        }
        
        /**
         * Convert UTF-8 Escape sequences in a string to UTF-8 Bytes
         * @return UTF-8 String
         * @param $str String
         */
        function _unescapeUTF8EscapeSeq($str) {
                return preg_replace_callback("/\\\u([0-9a-f]{4})/i", @create_function('$matches', 'return @Google_Translate_API::_bin2utf8(hexdec($matches[1]));'), $str);
        }
        
        /**
         * Convert binary character code to UTF-8 byte sequence
         * @return String
         * @param $bin Mixed Interger or Hex code of character
         */
        function _bin2utf8($bin) {
                if ($bin <= 0x7F) {
                        return chr($bin);
                } else if ($bin >= 0x80 && $bin <= 0x7FF) {
                        return pack("C*", 0xC0 | $bin >> 6, 0x80 | $bin & 0x3F);
                } else if ($bin >= 0x800 && $bin <= 0xFFF) {
                        return pack("C*", 0xE0 | $bin >> 11, 0x80 | $bin >> 6 & 0x3F, 0x80 | $bin & 0x3F);
                } else if ($bin >= 0x10000 && $bin <= 0x10FFFF) {
                        return pack("C*", 0xE0 | $bin >> 17, 0x80 | $bin >> 12 & 0x3F, 0x80 | $bin >> 6& 0x3F, 0x80 | $bin & 0x3F);
                }
        }
        
}
// Google Class

?>

Форма запуска:
HTML:
<form method='POST' enctype='multipart/form-data' >
<textarea name="links" rows="8" cols="90"></textarea><br />
<input type="hidden" name="parser_code" value=""/>
<input type='submit' name='ok' value='<?php echo $entry_code; ?>' /> 
</form>

Обработчик:

PHP:
<? // ЗАПУСК ФОРМЫ
if (isset($_POST['ok'])) {

$opisanie = 'English description product';

$title_product = 'Title product';


$trans_text = Google_Translate_API::translate($opisanie, 'en', 'ru');
$trans_title = Google_Translate_API::translate($title_product, 'en', 'ru'); 

echo '<br />'.$trans_text.'<br />'.$trans_title.'<br /><hr />'; 

// конец условия запуска формы
}
?>

Форма, класс и обработчик в одном файле.
После сработывания, выдает переведенный текст и ошибки:

Unknown: Non-static method Google_Translate_API::translate() should not be called statically, assuming $this from incompatible context in Z:\home\ocstore.loc\www\admin\view\template\module\parser.tpl on line 124Unknown: Non-static method Google_Translate_API::_unescapeUTF8EscapeSeq() should not be called statically, assuming $this from incompatible context in Z:\home\ocstore.loc\www\admin\view\template\module\parser.tpl on line 62Unknown: Non-static method Google_Translate_API::translate() should not be called statically, assuming $this from incompatible context in Z:\home\ocstore.loc\www\admin\view\template\module\parser.tpl on line 125Unknown: Non-static method Google_Translate_API::_unescapeUTF8EscapeSeq() should not be called statically, assuming $this from incompatible context in Z:\home\ocstore.loc\www\admin\view\template\module\parser.tpl on line 62

что с этим классом не так?
вроде вызвал нормально:

PHP:
$trans_text = Google_Translate_API::translate($opisanie, 'en', 'ru');
$trans_title = Google_Translate_API::translate($title_product, 'en', 'ru');
 
в php.ini вероятно прописано 'error_reporting = E_ALL|E_STRICT'
константа E_STRICT выдает варнинг при обращении к обычному (public) методу, как к статическому (static)

и как решение можно указать - error_reporting( E_ALL & ~E_STRICT );
или сделать методы класса статическими - "function f_name() { }" изменить на "static function f_name() { }"
 
Либо вызывать как не статику:

PHP:
Google_Translate_API = new Google_Translate_API();
$trans_text = Google_Translate_API->translate($opisanie, 'en', 'ru'); 
$trans_title = Google_Translate_API->translate($title_product, 'en', 'ru');
 
PHP:
function translate($text, $from = '', $to = 'en') {
заменить на
PHP:
public static function translate($text, $from = '', $to = 'en') {
Но лучше сделать как написано постом выше.
 
Назад
Сверху