Innervisions Innervisions - 1 month ago 6
PHP Question

Php oop echo-ing a single variable from within a class

I'm very new to PhP oop.I'm trying to make a small project here is my code:

class Language {

public $hello;
public $greetings;

public function english(){
echo $this->hello = "Hello" . "<br>";
echo $this->greetings = "Greetings" . "<br>";
}

public function british(){
echo $this->hello = "Ello there mate!" . "<br>";
echo $this->greetings = "Oi ya cheeky bugger" . "<br>";
}
}

$language = new Language;

echo $language->english();
echo $language->british();


How can I echo the variable $hello but only from 1 of the funcions? I really don't get the how I'm suppose to do it here.

Basically I want to grab $hello from english() and echo it out inside a

<p></p>


Or something along those lines

Can someone point me in the right direction?

Answer

You need to set the property then call it afterwards. I think you had your order mixed up.

class Language {

    public $hello;
    public $greetings;

    public function english(){
        $this->hello = "Hello" . "<br>";
        $this->greetings = "Greetings" . "<br>";
    }

    public function british(){
        $this->hello = "Ello there mate!" . "<br>";
        $this->greetings = "Oi ya cheeky bugger" . "<br>";
    }
}

$language = new Language;

$language->english();
echo $language->hello;

Maybe this is a bit more modular...

class Language {

    public $language = '';

    public $phrases = array(
        'UK' => array(
            'hello' => 'Ello gov\'na '
            'goodbye' => 'Good day!'
        ),
        'AUS' => array(
            'hello' => 'Alight mate? '
            'goodbye' => 'See ya later, mate'
        )
    );

    public function __construct($language = 'UK')
    {
        $this->language = $language;
    }

    public function say($phrase_key = 'hello')
    {
            return $this->phrases[$this->language][$phrase_key];
    }

}

$language = new Language('AUS');

echo $language->say('goodbye');
// See ya later, mate

// Just for fun