2017-09-10 26 views
0

雖然我知道如何在程序PHP中解決這個問題,但我遇到了OOP困難。一些代碼行被縮短了(例如html)。如何檢索這個OOP情況下的數組? [php]

因此,用戶輸入一個數字,$ army1在創建自己時將該對象傳遞給構造函數。我的構造函數使用for循環($ filled_army)填充數組,但我不知道如何以正確的方式檢索它(因此我可以在之後將其打印出來),因爲構造函數沒有返回值? 在構造函數中添加print_r($filled_army);將打印出值,只是提及。

此外,如果這個問題不應該通過__construct來解決,有人可以幫助我如何通過我自己的方法來做到這一點?我猜它應該與getter & setter完成,但我也有使用它們的問題,因爲一個變量在index.php中傳遞,而其他變量($ filled_army)是類的屬性...

的index.php

<form> 
    <input type="number" name="size"> 
</form> 

<?php 
    $army1 = new Army($_GET['size']); 
    // $army1->getArmy(); ?? 
?> 

army.class.php

<?php 
class Army { 
    public $filled_army = []; 
    public size; 
    //... 
    public function __construct($size){ 
     $this->size = $size; 
     $arrayOfSoldiers = [10,20,30]; 

     for($i=0; $i<$size; $i++) 
     { 
      $filled_army[$i] = $arrayOfSoldiers[mt_rand(0, count($arrayOfSoldiers) - 1)]; 
     } 
    } 
} 
?> 
+0

你能解釋一下prorcedural PHP和OOP之間的區別嗎?不清楚 – scaisEdge

回答

0

既然已經宣佈$filled_army財產public,這將提供正確的實例化後在PHP中使用標準的對象符號,例如:

$army1 = new Army($_GET['size']); 
$army1->filled_army; // Now contains your array; 

但是,屬性的​​可見性設置爲public意味着,任何代碼都可以修改屬性,不僅對象被創建通過。通常情況下,要解決這一點,我們設置的屬性要麼protectedprivate,然後使用getter/setter方法:

class Army 
{ 
    private $filled_army = []; 
    private $army_size = 0; 

    private static $_soldiers = [ 10, 20, 30 ]; 

    function __construct($size) 
    { 
    $this->army_size = $size; 

    for($i = 0; $i < $size; $i++) 
    { 
     $this->filled_army[] = self::$_soldiers[ mt_rand(0, count(self::$_soldiers) - 1) ]; 
    } 
    } 

    // Getter for the army: 
    public function getArmy() 
    { 
    return $this->filled_army; 
    } 

    // Getter for the size: 
    public function getArmySize() 
    { 
    return $this->army_size; 
    } 
} 

現在,我們可以訪問getArmy()方法(或類似的getArmySize()法):

$army1 = new Army($_GET['size']); 
$army1->getArmy();  // Returns the army 
$army1->getArmySize(); // Returns the value of $_GET['size']; 

還值得注意的是,PHP支持Magic Getters/Setters這可能對您的項目有用。

另請注意,我們不需要構造函數的可見性修飾符(PHP中的__construct()總是公開可見)。

+1

您在構造函數中忘記了$ this-> filled_army。當前寫入的方式,getArmy將始終返回一個空數組 – Erik

+0

@BenM首先,我嘗試編輯您的註釋,缺少'$ i'並在填充數組的行中關閉括號。其次,感謝你的代碼和一切的解釋。 我在你的評論前幾​​個小時查看了你的鏈接,但在我看來,這是一個錯誤的情況。 關於給定的代碼,我試過了,'$ army-> getArmy()'不起作用。我已經嘗試過,並且仍然無法完成工作。你有什麼想法可能是什麼原因?我像所做的一樣寫了所有內容,並提供了修正,並且仍然只能通過__construct中的for循環打印出'$ filled_army'。 –

+0

@IvanLoler請參閱編輯,我忘記了'filled_army'屬性上的'$ this'賦值,對不起!另外,'$ i'不是必需的,因爲無論如何你都要從它的'0'索引填充數組(數組在開始時總是空的)。 – BenM

相關問題