PHP: accessing variable string from class

hankknight
hankknight used Ask the Experts™
on
How can I get the value of var $foo?
<?php

class JConfig {
	var $foo = 'hello';
	var $zooph = 'world';
}

echo $JConfig->foo;

?>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
hi,
<?php

class JConfig{
  var $foo;
  var $zooph;

function JConfig {
        $this->foo = 'hello';
        $this->zooph = 'world';
}

}

in u other php page

$JConfigOBJ =new JConfig();

echo $JConfigOBJ->foo;

?>
Most Valuable Expert 2011
Top Expert 2016
Commented:
When you define your variables, choose public, private or protected.  The old "var" definition is a leftover from PHP4.  With public variables you can access them directly using OOP notation.  Your code may be better if you use "getters" and "setters" to access protected and private variables.

Private variables cannot be used when classes are extended.

Here is my teaching example of how you do it in PHP5.  Best, ~Ray
<?php // RAY_oop_vars.php
error_reporting(E_ALL);
echo "<pre>";

// DECLARE THE CLASS
Class MyOOP
{
    public  $my_public_var  = 'open';
    private $my_privat_var;

    // DECLARE THE CONSTRUCTOR
    public function __construct()
    {
        $this->my_privat_var = 'closed';
    }

    // DECLARE A FUNCTION TO SHOW THE VARIABLES
    public function show_vars()
    {
        echo "PUBLIC $this->my_public_var \n";
        echo "PRIVAT $this->my_privat_var \n";
        echo "\n";
    }

    // DECLARE ANOTHER FUNCTION TO SET THE PRIVATE VARIABLE
    public function set_privat($value)
    {
        $this->my_privat_var = $value;
    }
// END CLASS DECLARATION
}




// INSTANTIATE THE CLASS AND SHOW THE INITIAL VALUES OF VARIABLES
$a = new MyOOP;
$a->show_vars();

// SET A PRIVATE VARIABLE VIA THE FUNCTION
$a->set_privat('NewValue');

// SET A PUBLIC VARIABLE DIRECTLY
$a->my_public_var = 'Cheese';

// SHOW THE NEW VALUES
$a->show_vars();

// ACCESS A PUBLIC VARIABLE DIRECTLY
print_r($a->my_public_var);
echo "\n\n";

// DUMP THE VALUES FROM THE OBJECT
var_dump($a);

// TRY TO SET A PRIVATE VARIABLE THE WRONG WAY
$a->my_privat_var = 'Beer';

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial