Access var from PHP class

How can I echo the value of a var in a class?
<?php

class JConfig {
	var $hello = 'Hello World';
}


echo JConfig->hello;


?>

Open in new window

LVL 16
hankknightAsked:
Who is Participating?
 
Beverley PortlockCommented:
The class you have posted is a PHP4 class. In PHP5 there are things called ACCESS MODIFIERS. For example, consider this class

class Example {

     public $var1;            // "public" is PHP5's equivalent of "var" in PHP4
     protected $var2;
     private $var3;

}


Only $var1 is directly accessible

$ex = new Example();
$ex->var1 = "hello";
$ex->var2 = "world";

the second assignment will FAIL because $var2 is protected and making an assignment to $var3 will fail as well.

The private and protected variables can be accessed by SETTERS and GETTERS in the class itself



class Example {

     public $var1;            // "public" is PHP5's equivalent of "var" in PHP4
     protected $var2;
     private $var3;


     function getVar2() {
          return $this->var2;
     }


     function setVar2( $param ) {
          $this->var2 = $param;
     }
}



Then

$ex = new Example();
$ex->setVar2( "Hello world");
echo $ex->getVar2();

Lots more at http://www.php.net/oop
0
 
ludofulopCommented:
$jconfig = new JConfig();
echo $jconfig->hello;
0
 
72lionsCommented:
This will work on PHP 5:
<?php
class JConfig {
	var $hello = 'Hello World';
}

$jconfig = new JConfig();
echo $jconfig->hello;

?>

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.