1

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

2
  • echo str_replace($this->words,$this->replace,$roomlink); Commented Nov 8, 2015 at 12:46
  • 1
    Read this php.net/manual/en/language.oop5.php. Start with the introduction but read all the way through to atleast The Basics. You will spot your mistake. Commented Nov 8, 2015 at 13:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.