2012-09-01 59 views
-5

裏有的init.php碼3個編譯錯誤:未定義的變量問題

未定義的變量$ IND

未定義的變量$ popsize

未定義的變量$ CHROM

如何正確解決這個問題?

main.php

include_once 'init.php'; 

class Individual { 
    public $genes = array(); 
    //... 
} 

class Population { 
    public $ind = array(); 
    public $ind_ptr; 
    public function setIndPtr(Individual $ind) { 
     $this->ind_ptr = $ind; 
    } 
} 

$popsize = 10; 
$chrom = 5; 
$pop = new Population(); 
$pop_ptr = new Population(); 

$pop = init(pop_ptr); 

的init.php

function init(Population $pop_ptr) { 
     $pop_ptr->setIndPtr($ind[0]); 
     for ($i = 0 ; $i < $popsize ; $i++) { 
     for ($j = 0; $j < $chrom; $j++) { 
      $d = rand(0,1); 
      if($d >= 0.5) { 
      $pop_ptr->ind_ptr->genes[$j] = 1; 
      } 
      else { 
      $pop_ptr->ind_ptr->genes[$j] = 0; 
      } 
     } 
     $pop_ptr->setIndPtr($ind[$i+1]); 
     } 
     $pop_ptr->setIndPtr($ind[0]); 

     return $pop_ptr; 
    } 
+2

你的錯誤說的一切 - 沒有像「$ ind」這樣的數組,$ popsize和$ chrom在另一個範圍內定義。你可以讓它們成爲全局的,但更好的方法是通過參數傳遞給init函數。 – Cyprian

+0

@Cyprian:好的,init($ pop_ptr,$ popsize,$ chrom)幫助刪除了第二和第三個警告消息。但$ ind是在pop_ptr(類Population)中定義的。爲什麼在init中看不到? – Gusgus

+0

,因爲「ind」是pop_ptr的屬性。所以如果你想引用這個變量,你可以這樣做:$ pop_ptr-> ind [0](不是$ ind [0]) – Cyprian

回答

1

它的範圍的問題:變量是不共享的過文件,除非你讓他們全球!

(嚴重解釋)的變量,如

inc.php

$a=1; 

main.php

include "inc.php"; 
print $a 

將工作

然而

inc.php

function func() 
{ 
$a=1; 
} 

main.php

include "inc.php"; 
func(); 
print $a; 

一不可。

希望能讓它更清晰。在功能範圍

+0

好了,init($ pop_ptr,$ popsize,$ chrom)幫助刪除2nd和第三條警告信息。但$ ind是在pop_ptr中定義的。爲什麼無法看到以及如何解決這個問題?我是否也需要將它傳遞給函數'init'? – Gusgus

+1

變量* *共享「包含文件」。 – deceze

+0

@Core Xii:我知道我的問題是非常基本的。但是我仍然不明白爲什麼'ind'不能在'init'函數中看到,如果我傳遞'pop_ptr(Population class)。 'ind'是在Population類中定義的。 – Gusgus

0

全局變量需要全球使用前必須顯式聲明:

<?php 
function foo() 
    { 
    global $global_variable_from_outside_function_scope; 
    $global_variable_from_outside_function_scope += 1; 
    } 

至於$ind,有沒有這樣的變量存在。你想要更類似$pop_ptr -> ind。再次閱讀PHP docs在類,範圍等。

+0

Oook,現在我看到了.. – Gusgus

+0

$ pop_ptr-> setIndPtr($ pop_ptr - > $ ind [0]);爲什麼它說'$ ind = null'?它在Population類中定義爲$ ind = array()。 – Gusgus

+0

訪問對象屬性時,不要使用'$'美元符號。只需'$ pop_ptr - > ind [0]'。 –