search

Home  >  Q&A  >  body text

There is a problem with calling class attributes outside PHP classes. Could you please give me some advice?

<?php

class Animal{

  public $name;

  public $color;

  public function __construct($color){

    $this->color=$color;

  }

  function write($name){

    echo $this->name=$name." Can write!";

  }

  function run($name){

    echo $this->name=$name." Can run!";

  }

}

$dog=new Animal("yellow");

$dog->write("Dog");

echo '<br/>';

$sheep=new Animal("white");

$sheep->run("Sheep");

echo '<br/>';

echo " sheep color is ".$sheep->$color;  //这行报错,该怎么调用$color这个属性?

 ?>


BrianRawlingsBrianRawlings2421 days ago986

reply all(4)I'll reply

  • Mr.Robot

    Mr.Robot2018-04-12 13:38:56

    $sheep->color, do not need the $

    in front of color

    reply
    0
  • BrianRawlings

    Thank you. I used Java before, but now I want to learn PHP. I am used to the syntax of Java, so it is easy to make mistakes here and I can’t figure out why, haha

    BrianRawlings · 2018-04-12 13:50:44
  • 飞翔,期待、、、

    飞翔,期待、、、2018-04-12 10:34:43

    echo " sheep color is ".$sheep->color; //This line is written like this. If $ exists, color will become an undefined variable?

    reply
    0
  • BrianRawlings

    Thank you. I used Java before, but now I want to learn PHP. I am used to the syntax of Java, so it is easy to make mistakes here and I can’t figure out why, haha

    BrianRawlings · 2018-04-12 13:50:51
  • Cancelreply