We use MAMP for our servers and html/css/php files. I have double checked everything and im SURE this has no errors really. It ends up with a local host error. which means it won't display my work. Here is my work:
-- main.php --
<?php
require 'person.php'
$person = new Person;
$person->name = 'Froggy';
$person->age = '15';
echo $person->sentence();
?>
--- person.php ---
<?php
class Person {
public $name;
public $age;
public function sentence() {
return $this->name . 'is' . '$this->age' . ' years old';
}
}
?>
So this simple code would show me "'Froggy' is '15' years old" but it wont work. Help?
Parse error:
Add semi-colon here
require 'person.php';
Again, change function to:
public function sentence() {
return $this->name . ' is ' . $this->age . ' years old';
}
Issue was that $this->age
was having single quote around it.
Variables inside single quotes are not parsed, it is called variable interpolation.
Variables inside double quotes however, can be parsed.
Output:
Froggy is 15 years old
Remove the quotes around $this->age
:
<?php
class Person {
public $name;
public $age;
public function sentence() {
return $this->name . 'is' . $this->age . ' years old';
}
}
If you want the quotes in your output, you can return this in your function:
return "'$this->name' is '$this->age' years old";