Andurit
Andurit

Reputation: 5762

Variabile from constructor to method - PHP

i am pretty new in PHP OOP so I'm sorry if this question is noobish.

I choosing client langauge in constructor of the class. It looks like:

$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
         $_SESSION['lang'] = $lang;
         if(isSet($lang))
                setcookie('lang', $lang, time() + (3600 * 24 * 30));
            else if(isSet($_COOKIE['lang']))
                $lang = $_COOKIE['lang'];
            else
                $lang = 'cs';
        switch ($lang) 
        {
            case 'sk':
            $lang_file = 'sk.php';
            break;
            case 'cs':
            $lang_file = 'cs.php';
            break;
            default:
            $lang_file = 'cs.php';
        }
        include_once 'languages/'.$lang_file; 

AFter this if I add something like: echo $lang['YES'] to constructor it will display translate of it.

If I do add same echo to my other method I get error that $lang is undefined. So my question is how this work? How i can give all my methods in one class same variabile without using GLOBAL variabiles?

Thanks

EDITED: for example cs.php looks like:

$lang = array();

//All
$lang['YES'] = 'Ano';
$lang['NO'] = 'Ne';
$lang['NOT_AVALIABLE'] = 'Není k dispozici';
$lang['CURRENCY'] = 'Měna';

Start of my function looks like:

  public function fetchByVinAxnmrss($con) {
     $success = false;
     if($this->vin){
     try{
        $sql = "SELECT * FROM axnmrs_cases WHERE vin = :vin ORDER BY date_created DESC LIMIT 60";
        $stmt = $con->prepare( $sql );
        $stmt->bindValue( "vin", $this->vin, PDO::PARAM_STR );
        $stmt->execute();
            while ($row = $stmt->fetch()){
                echo"<tr>";
                echo  "<td class='number'>".$row['claimnumber']."</td>";
                echo $this->lang['AXNMRS_CASE_CREATED_DATE'];

Upvotes: 0

Views: 43

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

pass your $lang variable through constructor.

class YourClass {

   public $lang;
   public function __construct($lang) {
      $this->lang = $lang;
   }
}

$yourClass = new YourClass($lang)

Within your function try something like below:

public function fetchByVinAxnmrss($con) {
     global $lang; // grab $lang here and use later
     $success = false;
     ......
}

Upvotes: 1

Related Questions