I want to make variables and methods in php class. And want to use double quotes as I always use not in OOP. But it doesn’t work, it shows an error. Why? Here’s my code:
class myClass {
public $url = "http://www.somesite.com?index=$number"; // this var has url as a value
public $html = "<div> // this var is an HTML code with $url var in href
<a href='$url'>Link</a>
</div>";
public function echoHTML() { // and this is method to echo html code
echo $this->html;
}
}
$obj = new myClass();
$obj->echoHTML();
Problems are:
1) It shows error if double quotes are used here
public $url = "http://www.somesite.com?index=$number";
When I change double quotes for single quotes it works fine
public $url = 'http://www.somesite.com?index=$number';
Why? I used to always use double quotes in such not OPP coding and wouldn’t like to change my practice. Or I have to because single quotes are necessary in PHP OOP?
Also the same situation with the second variable $html. It makes me change outer double quotes for single quotes. And inner single qoutes to double ones. Like this:
public $html = '<div>
<a href="$url">Link</a>
</div>';
Ok, I change but here appears problem #2.
2) It doesn’t see value of variable in href. When page is loaded there’s $url in url but not http://www.somesite.com?index=$number as I expect. How to make him use a value of variable but not it’s name?
The usage of single vs double quotes has nothing to do with OOP or classes.
Double quotes tell PHP to evaluate the contents, so you can do stuff like
echo "text $var text";. When you use single quotes, the contents is not evaluated so this would not work.Concatenating strings generally gives a performance advantage over double quotes, so single quotes are usually advisable when combining text and variables, as you are. So consider this:
Notice that you must escape the double quotes in the anchor tag. It’s also convention to use double quotes for attribute values.