Hasnain Hayder
Hasnain Hayder

Reputation: 99

Undefined Variable within class

I recently made a class in PHP I am trying to declare a variable within class and using str_replace in a function but its show undefined variable

class Status{
  $words = array(".com",".net",".co.uk",".tk","co.cc");
  $replace = " ";
  function getRoomName($roomlink)
    {
      echo str_replace($words,$replace,$roomlink);

    }
}
$status = new Status;
echo $status->getRoomName("http://darsekarbala.com/azadari/");

Any kind of help would be appreciated thanks you

Upvotes: 1

Views: 165

Answers (2)

FirstOne
FirstOne

Reputation: 6217

Maybe because of the version or something, when I tested your exact code, I got syntax error, unexpected '$words' (T_VARIABLE), expecting function (T_FUNCTION), so setting your variables to private or public should fix this one.

About the undefined varible, you have to use $this-> to access them from your class. Take a look:

class Status{
    private $words = array(".com",".net",".co.uk",".tk","co.cc"); // changed
    private $replace = " "; // changed
    function getRoomName($roomlink){
        echo str_replace($this->words, $this->replace, $roomlink); // changed
    }
}
$status = new Status;
echo $status->getRoomName("http://darsekarbala.com/azadari/");

Also, since getRoomName isn't returning anything, echoing it doesn't do much. You could just:
$status->getRoomName("http://darsekarbala.com/azadari/");.
or change to :
return str_replace($this->words, $this->replace, $roomlink);

Upvotes: 0

Bjoern
Bjoern

Reputation: 16304

Your variables in the function getRoomname() aren't adressed properly. Your syntax assumes the variables are either declared within the function or passed while calling the function (which they aren't).

To do this within a class, do it while using $this->, like this:

function getRoomName($roomlink)
{
    echo str_replace($this->words,$this->replace,$roomlink);
}

For further informations, please have a look into this page of the manual.

Upvotes: 1

Related Questions