简体   繁体   中英

Why isn't my return function not working?

I'm learning Object oriented programming in PHP and in my course, the teacher uses the return function to print the function properties.

I tried it myself and nothing appeared. I then copy/pasted it and it's still not working. I know that's not normal, want to be sure if it's a WAMP issue or PHP7.2.18. Tried on chrome. When I went over 100, the error was here, which is normal.

When I wrote a letter, the error was also here.

But when I wrote a number between 0 and 100, it normally should return me my answer.

class Personnage
{
  private $_force;
  private $_experience;
  private $_degats;

  public function frapper(Personnage $persoAFrapper)
  {
    $persoAFrapper->_degats += $this->_force;
  }

  public function gagnerExperience()
  {
    $this->_experience++;
  }

  // Mutateur chargé de modifier l'attribut $_force.
  public function setForce($force)
  {
    if (!is_int($force)) // S'il ne s'agit pas d'un nombre entier.
    {
      trigger_error('La force d\'un personnage doit être un nombre entier', E_USER_WARNING);
      return;
    }

    if ($force > 100) // On vérifie bien qu'on ne souhaite pas assigner une valeur supérieure à 100.
    {
      trigger_error('La force d\'un personnage ne peut dépasser 100', E_USER_WARNING);
      return;
    }

    $this->_force = $force;
  }

  // Ceci est la méthode force() : elle se charge de renvoyer le contenu de l'attribut $_force.
  public function force()
  {
    return $this->_force;
  }
}
$perso = new Personnage;
$perso->setForce(100);
$perso->force();

The output should be 50, but, as I said, nothing.

If you want $perso->force(); as output you must echo it

echo $perso->force();

Usually nothing will be printed automatically, unless you render it (eg using echo or var_dump() ).

There are two possible ways:

  1. Instead of return use echo within the function. However, in this case you should change the function name to something like printForce() or renderForce() , to express what the function does.

  2. Use the return value outside of the function. You can either echo it directly by using echo $perso->force() or you save the return value to a variable: $force = $perso->force() and print the value of $force somewhere else in your code. Renaming the function would also make sense here: getForce() would be more sufficient to express, that the function will return some value.

使用return不会显示数据,您应该使用echo / print / etc来显示“ return”数据值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM