php5中的引用存在问题
让我从代码开始:php5中的引用存在问题,php,class,object,reference,Php,Class,Object,Reference,让我从代码开始: <?php class Father{ function Father(){ echo 'A wild Father appears..'; } function live(){ echo 'Some Father feels alive!'; } } class Child{ private $parent; function Child($p){ echo 'A chi
<?php
class Father{
function Father(){
echo 'A wild Father appears..';
}
function live(){
echo 'Some Father feels alive!';
}
}
class Child{
private $parent;
function Child($p){
echo 'A child is born :)';
}
function setParent($p){
$parent = $p;
}
function dance(){
echo 'The child is dancing, when ';
$parent -> live();
}
}
$p = new Father();
$p -> live();
$c = new Child($p);
$c -> dance();
?>
运行此命令时,我在第24行收到一个错误,上面写着“PHP致命错误:在第24行的../test.PHP中对非对象调用成员函数live()”
我已经在网络上搜索了一段时间,但找不到解决方案。
有人能帮我解决我对php5的理解不好的问题吗?您需要使用
$this->parent->live()
来访问成员变量。此外,还必须将父对象指定给它
class Child{
private $parent;
function __construct($p){
echo 'A child is born :)';
$this->parent = $p; // you could also call setParent() here
}
function setParent($p){
$this->parent = $p;
}
function dance(){
echo 'The child is dancing, when ';
$this->parent -> live();
}
}
除此之外,您应该将构造函数方法重命名为
\u construct
,这是PHP5中建议的名称。您需要使用$this->parent->live()
访问成员变量。此外,还必须将父对象指定给它
class Child{
private $parent;
function __construct($p){
echo 'A child is born :)';
$this->parent = $p; // you could also call setParent() here
}
function setParent($p){
$this->parent = $p;
}
function dance(){
echo 'The child is dancing, when ';
$this->parent -> live();
}
}
除此之外,您应该将构造函数方法重命名为
\u construct
,这是PHP5中建议的名称。您没有在构造函数中调用setParent
。这将解决它:
function Child($p){
echo 'A child is born :)';
$this->setParent($p);
}
您没有在构造函数中调用
setParent
。这将解决它:
function Child($p){
echo 'A child is born :)';
$this->setParent($p);
}
首先,在PHP5中使用构造函数的首选方法是使用_construct关键字。 当您访问类成员时,您应该使用
$this
,在您的情况下,当您尝试创建父类成员时,您没有使用此开关
function setParent($p){
$parent = $p;
}
这样做:
function setParent($p){
$this->parent = $p;
}
这是:
function dance(){
echo 'The child is dancing, when ';
$parent -> live();
}
为此:
function dance(){
echo 'The child is dancing, when ';
$this->parent -> live();
}
您将以以下内容结束:
$p = new Father();
$p -> live();
$c = new Child();
$c -> setParent($p);
$c -> dance();
您不需要将父构造函数传递给子构造函数,因为您将在setParent
方法中设置它 首先,在PHP5中使用构造函数的首选方法是使用_construct关键字。
当您访问类成员时,您应该使用$this
,在您的情况下,当您尝试创建父类成员时,您没有使用此开关
function setParent($p){
$parent = $p;
}
这样做:
function setParent($p){
$this->parent = $p;
}
这是:
function dance(){
echo 'The child is dancing, when ';
$parent -> live();
}
为此:
function dance(){
echo 'The child is dancing, when ';
$this->parent -> live();
}
您将以以下内容结束:
$p = new Father();
$p -> live();
$c = new Child();
$c -> setParent($p);
$c -> dance();
您不需要将父构造函数传递给子构造函数,因为您将在setParent
方法中设置它 您知道在PHP5中构造函数应该命名为\u construct
,而不是类的名称吗?不,我不知道。我只是在学习这门语言,因为我得为一个项目写点东西。谢谢您的建议:)您知道在PHP5中构造函数应该命名为\u construct
而不是类的名称吗?不,我不知道。我只是在学习这门语言,因为我得为一个项目写点东西。谢谢你的建议:)啊!知道这一点很好:)-9分钟后,这可能成为解决方案^^Aah!知道这一点很好:)-9分钟后,这可能成为解决方案^^通常getter/setter用于外部接口,内部直接访问字段更好。通常getter/setter用于外部接口,内部直接访问字段更好。