call class php code example

Example 1: create a class in php

<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function get_name() {
    return $this->name;
  }
  function get_color() {
    return $this->color;
  }
}

$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

Example 2: php call class method by string

class Player {
    public function SayHi() { print("Hi"); }
}
$player = new Player();

call_user_func(array($player, 'SayHi'));
// or
$player->{'SayHi'}();
// or
$method = 'SayHi';
$player->$method();

Tags:

Php Example