2014-01-14 28 views
-1

我必须调用类中的变量。我怎么能够?类内调用变量

page1.php中

<?php 

$conn = array('1','2','3'); 

?> 

使page2.php

<?php 

class Test 
{ 
//here i want the $conn variable 
} 

?> 
+2

在'page2.php'中包含'page1.php'' – Roopendra

+0

使用全局作用域变量不是真正的OOP风格。我建议使用类属性或常量。 – Xardas

+0

@Roopendra:但不能在课堂内访问$ conn。 Plz给我你的答案。 – next2u

回答

1

a.php只会

$conn = array('1','2','3'); 

可以包括网页上面和
在你的类:

include("a.php"); 
class Test 
    { 
     public $arr; 
     function __construct($arr){ 
      $this->arr = $arr; 

     } 

    } 
    $t1 = new Test($conn);//pass the array from above page in the class 
    print_r($t1->arr); 

输出:

Array ([0] => 1 [1] => 2 [2] => 3) 
+0

@deepus:你想要这个吗? –

+0

工作..谢谢... – next2u

+0

@deepus:如果它的工作,那么你应该接受它:) –

2

page1.php中

$conn = array("1","2","3","4"); 

使page2.php

include 'Page1.php'; 

class Test { 
    function __construct($var){ 
     $this->param = $var; 
    } 
} 

$newTest = new Test($conn); 
var_dump($newTest->param); 
//prints the array $conn 

当然,您可以根据自己的喜好重新命名变量。

1

您无法直接访问类内的变量。您可以使用全局变量的作用域

你可以这样做,以及: -

include 'page1.php'; 

class Test { 

    public function test1() { 
     global $conn; 
     return $conn; 
    } 

} 

$testObj = new Test; 
print_r($testObj->test1()); 
+0

感谢..它的工作 – next2u

+0

很高兴帮助你;) – Roopendra