2014-12-10 93 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

除此之外,您通常应该避免在“定义类”文件中出现“做东西”代码。