2014-12-10 129 views
-1

我想從一個PHP文件中的信息傳遞給另一個class.php我似乎無法能夠從以.php

這個信息傳遞到另一個.PHP類文件是我在我的main.php

<?php 
require 'combinations.php'; 
$string = "12345"; 
$num = 2; 

$c = Combinations($string, $num); 

echo $c; 
?> 

我想通過$ string和$ num,這將從我的主文件更改爲組合類。

這是我combinations.php

<?php 
class Combinations implements Iterator 
{ 
    protected $c = null; 
    protected $s = null; 
    protected $n = 0; 
    protected $k = 0; 
    protected $pos = 0; 

    function __construct($s, $k) { 
     if(is_array($s)) { 
      $this->s = array_values($s); 
      $this->n = count($this->s); 
     } else { 
      $this->s = (string) $s; 
      $this->n = strlen($this->s); 
     } 
     $this->k = $k; 
     $this->rewind(); 
    } 
    function key() { 
     return $this->pos; 
    } 
    function current() { 
     $r = array(); 
     for($i = 0; $i < $this->k; $i++) 
      $r[] = $this->s[$this->c[$i]]; 
     return is_array($this->s) ? $r : implode('', $r); 
    } 
    function next() { 
     if($this->_next()) 
      $this->pos++; 
     else 
      $this->pos = -1; 
    } 
    function rewind() { 
     $this->c = range(0, $this->k); 
     $this->pos = 0; 
    } 
    function valid() { 
     return $this->pos >= 0; 
    } 
    protected function _next() { 
     $i = $this->k - 1; 
     while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i) 
      $i--; 
     if($i < 0) 
      return false; 
     $this->c[$i]++; 
     while($i++ < $this->k - 1) 
      $this->c[$i] = $this->c[$i - 1] + 1; 
     return true; 
    } 
} 
foreach(new Combinations($string, $num) as $substring) 
    echo $substring, ' '; 
?> 

這是我得到的錯誤:

注意:未定義的變量:字符串在C:\ XAMPP \ htdocs中\ recSII \上線58 combinations.php
注意:Undefined variable:num中的C:\ xampp \ htdocs \ recSII \ combinations.php第58行
致命錯誤:調用未定義的函數Combinations()在C:\ xampp \ htdocs \ recSII \ main.php上第6行
致命的錯誤行將是$ c =組合($ string,$ num);

+0

檢查PHP文檔的require()和include() – RobP 2014-12-10 23:10:10

+0

(1)從類定義文件中刪除foreach循環。 (2)將'$ c = Combinations($ string,$ num);'改爲'$ c = new Combinations($ string,$ num);'(3)''echo''對象可能不會達到你期望的效果... – Wrikken 2014-12-10 23:10:23

回答

0

require該文件首先,在實際定義它使用的變量之前。在定義變量後,執行require

除此之外,您通常應該避免在「定義類」文件中出現「做東西」代碼。