0

I am trying to get into php object oriented programming.

<?php
class myClass{

public $myVar="this is demo";

public function myTextdemo(){
        echo $myVar;
    }
}
$obj= new myClass;
echo $obj->$myVar;

?>

It says

Fatal error: Cannot access empty property on line 11

What's wrong with my code?

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by arunpawar
1

Change it like this:

<?php
class myClass
{
    public $myVar="this is demo";

    public function myTextdemo()
    {
        return $this->myVar; # the problem was here
    }
}

$obj = new myClass();
echo $obj->myVar; # and here you wrote $obj->$myVar with an extra $
?>

use return to output data from a function not echo and use $this inside the class functions, otherwise the declared property will not be considered and you will get an error like Undefined variable...

http://www.php.net/manual/en/language.oop5.properties.php

bye! :)

Edited by cereal

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.