【问题标题】:Access variable from outrside of class从类外访问变量
【发布时间】:2015-05-15 16:38:54
【问题描述】:

我有一个小问题:

可以说:我有一个脚本来翻译我的网站。它或多或少是这样的:

//getting browser language
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if($lang !== 'pt'){
    $lang == 'en';
}

比我包含几个具有翻译数组的 php 文件之一:

$path = 'languages/';
include_once($path.$lang.'.php');

翻译数组示例:

//pt.php
$translate = array(
'Hello' => 'Olá',
'World' => 'mundo'
); 

所以,现在的主要想法是有一个单词类,它可以让这个数组翻译字符串并将第一个字母变成大写。所以我现在拥有的:

//class word.php

class word {
    public function translate($lang, $string){
        global $translate;
        include('languages/'.$lang.'.php');
        $string = $translate['hello'];
        return $string;
    }

    function uc_sentence($string){
        $string = ucfirst(strtolower($string));
        $string = preg_replace_callback('/[.!?].*?\w/', create_function('$matches', 'return strtoupper($matches[0]);'),$string);
        echo $string;
    }
}

那么,这里发生了什么? 我可以这样做:

$word = new word();
$word->translate('pt',$string);
$word->uc_sentence($string);

它会输出翻译后的字符串。但在我看来,这就像一个非常糟糕的编码。

我的想法是让 include_once('pt.php') 可用于类中的所有函数,然后在 uc_sentence 中运行翻译。

我怎样才能做到这一点。

【问题讨论】:

    标签: php function class


    【解决方案1】:

    将数组作为word 构造函数的参数传入:

    class word {
        private $words;
    
        public function __construct(array $words) {
            $this->words = $words;
        }
    
        // rest of class here
    }
    
    // When translating:
    $word = new word($translate);
    $word->translate('fr', $string);
    

    这个概念被称为依赖注入,但是如果你有更多的数组要传递,我会这样做:

    class word {
    
        private $words = array();
    
        public function __construct(array $words) {
            $this->addWords($words);
        }
    
        public function addWords(array $words) {
            $this->words = array_merge($this->words, $words);
        }
    
        // rest of class here
    
    }
    

    【讨论】:

    • 建议加一个。为什么不将其设为protected,以便全家人都能享受$words 的乐趣? ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    相关资源
    最近更新 更多