Maarten Hartman
Maarten Hartman

Reputation: 1629

echo variables from a class

I need to know how I can echo $host from the following class:

class JConfig {

    public $host = 'localhost';

}

any ideas?

Thanks!

Upvotes: 2

Views: 14473

Answers (2)

Surreal Dreams
Surreal Dreams

Reputation: 26380

bcmcfc is correct - this will echo your variable. However, the best practice is to make a "getter" function. This function retrieves the value of the value for you. This goes in conjunction with a "setter" function which is used to set the value. Here's an example of a getter (and a setter, for extra reference) for this value:

class JConfig {

    private $host = 'localhost';

    //Getter function for $host
    public function getHost() {
        return $this->host;
    {

    //Setter function for $host
    public function setHost($value) {
        $this->host = $value;
    {

}

Then you call your setter and getter to access this variable.

$jc = new JConfig();

//set it
$jc->setHost("MyHost");

//get it
echo $jc->getHost();

Here's a good article on the subject: http://www.mustap.com/phpzone_post_203_setter-and-getter

It's a little more work, but it lets you do things inside the class like check values you set for validity, do calculations, format text, etc. You can also add units to values, round numbers, lie about your age... the list goes on. These apply to both get and set functions. The best part of this is that when you build a class this way, you don't have to update the scripts using the class - you just update the class itself.

When you get into larger numbers of data members of your class, you can look into magic methods.

Upvotes: 4

bcmcfc
bcmcfc

Reputation: 26745

$jc = new JConfig();
echo $jc->host;

You may want to look into static variables though.

Upvotes: 12

Related Questions