Page 1 of 1

Cannot access empty property

Posted: Sun Apr 25, 2010 12:54 am
by khuzema
Hi folks i have written below code
----------------------------------------------------------------------
<?php
class test
{
var $msg;
function test()
{
$this->msg="Hi hw r u";
}
}

$ob=new test();
echo $ob->msg;
?>
--------------------------------------------------------------------
when i am placing $ sign before the name of class member variable "msg" in the line "echo $ob->msg" i am getting error
"Cannot access empty property"

Now my question is why we cannot access member variables of a class using "$" sign before there names i.e why i am getting the above error ?
Any kind of help is highly appreciable

Re: Cannot access empty property

Posted: Sun Apr 25, 2010 1:25 am
by Zyxist
Because we access them without a dollar sign. This is how the PHP syntax was defined:

Code: Select all

// Read the "foo" property"
echo $object->foo;
If you add a dollar sign, PHP tries to read the property name from a variable:

Code: Select all

// This reads the "foo" property, too, but now
// the name is stored in a variable.
$propertyName = 'foo';
echo $object->$propertyName;
If your variable does not exist or is empty, PHP thinks you are trying to access a property with an empty name and generates such error.

Re: Cannot access empty property

Posted: Sun Apr 25, 2010 10:55 pm
by khuzema
Thanks Zyxist i got your point but when i tried your technique in below code i am left with an empty output
--------------------------------------------------------------------------------
<?php
class test
{
var $amount;
function test()
{
$amount=500;
}
function display()
{
$propname='amount';
echo $this->$propname;
}
}
$ob= new test();
$ob->display();
?>
----------------------------------------------------------------------------------------------------------
the above code should display 500 in the output but the o/p is blank plz help me on this
Thanks
Regards
Khuzema

Re: Cannot access empty property

Posted: Mon Apr 26, 2010 12:51 am
by flying_circus
You need to declare class properties as public, protected, or private. Get rid of the "var" keyword. Also, you should get in the habit of using the constructor __construct() rather than same function name as class constructor.

Code: Select all

<?php
  class test
  {
  # Class Properties
    public $amount = 0;
    
    //function test() {
    function __construct() {
      $this->amount = 500;
    }
    
    function display() {
      $propname = 'amount';
      echo $this->$propname; // Output: "500"
      echo $propname; // Output: "amount"
      echo $this->amount; // Output: "500"
    }
  }
  
  $ob = new test();
  $ob->display();
?>

Re: Cannot access empty property

Posted: Mon Apr 26, 2010 1:49 am
by khuzema
Thanks flying_circus i will follow your advice

Regards
Khuzema Dharwala