Abhilash Muthuraj
Abhilash Muthuraj

Reputation: 2028

php code is not executing?

<?php
class abhi
{
    var $contents="default_abhi";

    function abhi($contents)
    {
        $this->$contents = $contents;
    }

    function get_whats_there()
    {
        return $this->$contents;
    }

}

$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();

?>

i've initialized variable contents a default and also constructor, why is the value not printing, anything i should correct here?

see the error,

abhilash@abhilash:~$ php5 pgm2.php 

Fatal error: Cannot access empty property in /home/abhilash/pgm2.php on line 13
abhilash@abhilash:~$ 

Upvotes: 1

Views: 206

Answers (7)

VolkerK
VolkerK

Reputation: 96159

Since the question is tagged as "php5" here's an example of your class with php5 class notation (i.e. public/protected/private instead of var, public/protected/private function, __construct() instead of classname(), ...)

class abhi {
  protected $contents="default_abhi";

  public function __construct($contents) {
    $this->contents = $contents;
  }

  public function get_whats_there() {
    return $this->contents;
  }
}

$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();

Upvotes: 5

Radu M.
Radu M.

Reputation: 5738

You have a problem with $: 1. when using $this-> you do not put $ between "->" and the variable name the "$" sign, so your $this->$contents should be $this->contents. 2. in your echo youforgot the $ when calling that function from the instantiated class.

So your correct code is:

<?php
class abhi
{
    var $contents="default_abhi";

    function abhi($contents)
    {
        $this->contents = $contents;
    }

    function get_whats_there()
    {
        return $this->contents;
    }

}

$abhilash = new abhi("abhibutu");
echo $abhilash->get_whats_there();

?>

Upvotes: 0

Softnux
Softnux

Reputation: 2730

Also, are you not missing a dollar-sign in "echo abhilash->get_whats_there();"? ($abhilash->..)

Upvotes: 1

appusajeev
appusajeev

Reputation: 2299

use $this->contents
i too at first had the same problem

Upvotes: 0

Extrakun
Extrakun

Reputation: 19315

You are returning the variable incorrectly inside the function. It should be:

return $this->contents

Upvotes: 14

Simon
Simon

Reputation: 37978

Should be accessing and writing to $this->contents not $this->$contents

Upvotes: 3

Psytronic
Psytronic

Reputation: 6113

If i recall correctly it would be

$this->contents = $contents;

not

$this->$contents = $contents;

Upvotes: 4

Related Questions