php公共函数不在类外工作

时间:2017-06-14 01:51:41

标签: php class oop php-5.6 public-method

我创建了一个简单的类,变量和公共函数。当我尝试启动一个对象并从类外部的类调用public函数时,我得不到我能看到的输出。

<?php
error_reporting(E_ALL);
ini_set("error_reporting", 1);

  class Game {
    var name;

    public function show_game() {
      echo $this->name;
    }
  }

  $game = new Game;
  $game->name = "testing game";

  $game->show_game();
?>

根据我的理解,该功能应该回显测试游戏。但是当我加载页面时,我没有看到任何输出。

2 个答案:

答案 0 :(得分:1)

var name;

语法无效,请更改为:

var $name;

答案 1 :(得分:0)

您似乎忘记了PHP变量中的$var name应为var $name

<?php
  class Game {
    var $name;
    public function show_game() {
      echo $this->name; // Returns "testing game"
    }
  }
  $game = new Game;
  $game->name = "testing game";
  $game->show_game();
?>

希望这有帮助! :)