-2
<?php

class spel {

  function randomWoord() {
      $woorden = array(
          'Juan',
          'Luis',
          'Pedro',
          // and so on
        );
      return $woorden[rand ( 0 , count($woorden) -1)];
  }

  print randomWoord();

  }

?>

New to programming, function does not work inside class. When I remove the class, it does work. How can I fix this.

Shikaziku
  • 3
  • 3
  • 1
    You must learn what classes are. [w3schools](https://www.w3schools.com/php/php_oop_classes_objects.asp) – CoderCharmander Feb 28 '20 at 07:44
  • You need to read up on how objects work, your `print` just causes a syntax error. Remove this and add (outside the class) `$s= new spel(); print $s->randomWoord();`, this creates an object of that class and then calls the function using that object. – Nigel Ren Feb 28 '20 at 07:44
  • Does this answer your question? [php callback function in class](https://stackoverflow.com/questions/12179552/php-callback-function-in-class) – ThienSuBS Feb 28 '20 at 07:44
  • What do you mean with function doesnt'work? I'll suggest you to read a good tutorial about how class works – Sfili_81 Feb 28 '20 at 07:44

1 Answers1

1

You should create an object for call any method from the class.

<?php

 class spel {

  function randomWoord() {
    $woorden = array(
      'Juan',
      'Luis',
      'Pedro',
      // and so on
    );
    return $woorden[rand ( 0 , count($woorden) -1)];
  }
 }

$obj = new spel ();
echo $obj->randomWoord();
?>

Try This code

Tushar
  • 568
  • 3
  • 13