2017-07-02 52 views
-1

任何人都可以告訴我爲什麼我的角色統計不會打印?我沒有收到任何錯誤或語法消息..爲什麼我的變量不打印? PHP

這是我的第一個php項目。我無法弄清楚我錯過了什麼!

<? 
    class character{ 
     public $healthpoints = 100; 
     public $isdead = false; 
     public $class = "Mage"; 
     public $level = 10; 
    } 


    function checkdeath() { 
    if($healthpoints >= 0){ 
     $isdead = true; 
     } 
    } 

    new character(); 

    function CharStats() { 
     echo $healthpoints; 
     echo $isdead; 
     echo $class; 
     echo $level; 
    } 

    CharStats; 


    ?> 
+0

這是一個可變範圍問題 - http://php.net/manual/en/language.variables.scope.php。你的類變量不在你函數的範圍內。簡單的解決方案是將你的函數作爲類方法添加到你的類中 – Sean

+0

它從讀取錯誤消息開始:https://3v4l.org/he30R – hakre

回答

2

我想不通,我錯過了什麼!

思考,ALL

class Character{ 
    public $healthpoints = 100; 
    public $isdead = false; 
    public $class = "Mage"; 
    public $level = 10; 

    function checkdeath() { 
     if($this->healthpoints >= 0){ 
     $this->isdead = true; 
     } 
    } 

    function CharStats() { 
     echo $this->healthpoints; 
     echo $this->$isdead; 
     echo $this->$class; 
     echo $this->$level; 
    } 

} 

$character = new Character(); 
$character->ChatStats(); 

再次閱讀類/對象/等。 - Classes and Objects in PHP

+0

類方法不應該回顯任何內容。也許超出範圍,但返回一個sttring,然後通過__toString()代理,然後echo'ing對象變量可能是(更)適當的。 – hakre

+0

非常好,謝謝你們,我完全按照我的意願工作。我將我的$ isdead更改爲僅爲yes或no的字符串。 – DragonKyn