2012-01-30 76 views
0

我需要在php中編寫一個Player類,它與一個我不允許更改的函數一起工作。我必須以這個函數返回最大值的方式編寫這個類。我只能使用1-10之間的整數。我這裏只複製有問題的一部分:PHP中的嚴格比較

function CalcPlayerPoints($Player) { 

$Points = 0; 

    foreach($Player as $key => $Value) { 

    switch ($key) { 
    case "profyears": 
     if($Value===true) // this should be true 
     $Points+=($Value*5); // this should take tha value I give in the class construct 
     break; 
    case "gentleman": 
     if($Value===true) 
     $Points+=10;     
     break; 
    } 
    } 
return $Points; // that should be maximized 
} 

既然我不能改變===比較,我不能初始化profyears屬性。如果我有10初始化,那麼它不if語句輸入...

public function __construct() { 
    $this->gentleman = true; 
    $this->profyears = 10; 
} 
+1

你的問題是什麼? – Crontab 2012-01-30 17:57:19

+2

如果$ value === true,那麼您如何期望解釋器將此乘以5? – JConstantine 2012-01-30 17:59:23

+0

如何調用'CalcPlayerPoints'? – 2012-01-30 18:00:33

回答

0

此功能允許唯一的選擇就是profyears是一個布爾值,所以真或假。沒有其他選擇可能。

所以這個班級處理的不是年份,而是因爲是否有工作經驗。因此,__construct中唯一正確的值是true或false。這可能是一個奇怪的命名轉換。例如,它會命名爲hasProfYears是有意義的。

一些例子:
與profyears君子得:15分。
一個非紳士與profyears給5分。
沒有年紀的紳士給出10分。
一位無紳士的非紳士給出0分。

0

該功能不能像創作者所預期的那樣工作。 $Value變量被嚴格評估爲布爾值,但是它對其執行數學運算。如果不修改原始功能,則無法解決此問題。

此外,似乎有一個缺少的右括號。

稱爲功能是:

function index() 
{ 
    var_dump($this->CalcPlayerPoints(array('profyears' => 10))); 
} 

function CalcPlayerPoints($Player) { 

    $Points = 0; 

    foreach($Player as $key => $Value) { 

     switch ($key) { 
      case "profyears": 
       if($Value===true) // this should be true 
       $Points+=($Value*5); // this should take tha value I give in the class construct 
       break; 
      case "gentleman": 
       if($Value===true) 
       $Points+=10;     
       break; 

     } 
    } 
return $Points; // that should be maximized 
} 

將顯示int 0每次不管所提供內容的整數值。如果原來的功能,可以進行修改,以消除類似的嚴格比較:

function index() 
{ 
    var_dump($this->CalcPlayerPoints(array('profyears' => 10))); 
} 

function CalcPlayerPoints($Player) { 

    $Points = 0; 

    foreach($Player as $key => $Value) { 

     switch ($key) { 
      case "profyears": 
       if($Value==true) // this should be true 
       $Points+=($Value*5); // this should take tha value I give in the class construct 
       break; 
      case "gentleman": 
       if($Value==true) 
       $Points+=10;     
       break; 

     } 
    } 
return $Points; // that should be maximized 
} 

該函數將返回預期的結果:int 50

+0

認爲值得一提的是,函數需要引用一個對象(舊的&引用樣式)而不是數組。 – 2012-01-30 18:24:43

+0

有問題的函數沒有區別。 OP似乎以這種方式使用它,但是一個數組對於這個函數來說是一個完全有效的參數,這對於測試來說應該足夠了。 – 2012-01-30 18:27:10

+0

如果沒有提到你會是正確的: *我只在這裏複製了問題的一部分* 那是在這個話題開始提及。 $ Player也以大寫P開頭,通常表示一個對象。所以它可能會影響我們在這裏看不到的部分,這就是爲什麼我記下它以防止後來的問題。 – 2012-01-30 18:31:19

0

看來CalcPlayerPoints功能有一個錯誤,因爲它使感知做到這一點:

if ($Value === true) 
    $Points += $Value * 5; 

即,「TRUE times 5」並不意味着什麼。