We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,874 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Can't access empty property?

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
1 Hour
Discussion Span
9 Months Ago
Last Updated
3
Views
Question
Answered
arunpawar
Junior Poster in Training
66 posts since Dec 2007
Reputation Points: 9
Solved Threads: 0
Skill Endorsements: 0

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! :)

cereal
Veteran Poster
1,144 posts since Aug 2007
Reputation Points: 344
Solved Threads: 222
Skill Endorsements: 22

Awesome. Solved. THanks cereal :)

arunpawar
Junior Poster in Training
66 posts since Dec 2007
Reputation Points: 9
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 9 Months Ago by cereal

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0633 seconds using 2.66MB