我们使用MAMP作为我们的服务器和html/css/php文件。我已经仔细检查了所有内容,我确定这真的没有错误。它最终导致本地主机错误。这意味着它不会显示我的作品。这是我的工作:
--主要.php --
<?php
require 'person.php'
$person = new Person;
$person->name = 'Froggy';
$person->age = '15';
echo $person->sentence();
?>
---人.php ---
<?php
class Person {
public $name;
public $age;
public function sentence() {
return $this->name . 'is' . '$this->age' . ' years old';
}
}
?>
所以这个简单的代码会告诉我"'青蛙'是'15'岁",但它不起作用。帮助?
解析错误:
在此处添加分号
require 'person.php';
同样,将函数更改为:
public function sentence() {
return $this->name . ' is ' . $this->age . ' years old';
}
问题是$this->age
周围有单引号。
单引号内的变量不被解析,称为变量插值。
但是,可以解析双引号内的变量。
输出:
Froggy is 15 years old
删除$this->age
两边的引号:
<?php
class Person {
public $name;
public $age;
public function sentence() {
return $this->name . 'is' . $this->age . ' years old';
}
}
如果你想在
输出中使用引号,你可以在函数中返回:
return "'$this->name' is '$this->age' years old";