[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 336
  • Last Modified:

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

0
hankknight
Asked:
hankknight
3 Solutions
 
ludofulopCommented:
$jconfig = new JConfig();
echo $jconfig->hello;
0
 
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
 
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now