我必须在类中调用变量。我怎么能?
page1.php中
<?php
$conn = array('1','2','3');
?>
使page2.php
<?php
class Test
{
//here i want the $conn variable
}
?>
答案 0 :(得分: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 :(得分:1)
您无法直接访问类中的变量。你可以使用全局变量范围
你也可以这样做: -
include 'page1.php';
class Test {
public function test1() {
global $conn;
return $conn;
}
}
$testObj = new Test;
print_r($testObj->test1());
答案 2 :(得分: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 )