代码运行没有错误,但名字不显示是为什么?

来源:4-1 对象继承-PHP面向对象编程

祁望

2016-05-12 09:22

  <p><?php

class Human

{

public $name;

public $height;

public $weight;

public function eat($food){

echo $this ->name."'s eating ".$food."\n";

}

}

class Player extends Human 

{

}


$jor=new Human("jor","198cm","75kg");

echo $jor ->name."\n";

$jor ->eat("orange");

?>


写回答 关注

6回答

  • 保龙
    2016-05-18 12:56:47
    已采纳

    你new错了,要new Player类

    <?php

    class Human{

    public $name;

    public $height;

    public $weight;


    public function eat($food){

    echo $this->name."'s eating ".$food."\n";

    }

    }


    class Player extends Human{

    function __construct($name,$height,$weight){

    $this->name=$name;

    $this->height=$height;

    $this->weight=$weight;

    }

    }


    $jor = new Player("jor","198cm","75kg");

    echo $jor->name."\n";

    $jor->eat("orange");

    ?>


    祁望

    可以了,非常感谢!

    2016-05-18 13:39:03

    共 1 条回复 >

  • qq_一場煙火半世迷離_0
    2016-07-14 11:42:37

    new  子类不是父类

  • 祁望
    2016-05-16 10:44:53

    可不可以帮我把代码直接改好啊?我把构造函数加入Human类里,name也没出来

  • ewang1986
    2016-05-14 14:15:34

    构造函数加到Human类里面

  • 祁望
    2016-05-12 11:50:50

      <p><?php

    class Human

    {

    public $name;

    public $height;

    public $weight;

    public function eat($food){

    echo $this ->name."'s eating ".$food."\n";

    }

    }

    class Player extends Human 

    {

    function __construct($name,$height,$weight)

    $this->name=$name;

    $this->height=$height;

    $this->weight=$weight;

    }


    $jor=new Human("jor","198cm","75kg");

    echo $jor ->name."\n";

    $jor ->eat("orange");

    ?>

    加了构造函数还是没显示

  • Nick_Li551
    2016-05-12 10:46:53

    你没写构造函数,你的数据没有录进去$jor里面,$jor用的是你定义的类里面的原来的name height weight 就是空的

PHP面向对象编程

从容应对面试官的知识宝典,带你握面向对象的最重要的核心能力

70153 学习 · 361 问题

查看课程

相似问题