Php 在类内调用变量

Php 在类内调用变量,php,class,Php,Class,我必须在类中调用一个变量。我该怎么办 page1.php <?php $conn = array('1','2','3'); ?> page2.php <?php class Test { //here i want the $conn variable } ?> Page1.php $conn = array("1","2","3","4"); Page2.php include 'Page1.php'; class Test { func

我必须在类中调用一个变量。我该怎么办

page1.php

<?php

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

?>

page2.php

<?php

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

?>

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

当然,您可以随意重命名变量。

您不能直接访问类内的变量。您可以使用全局变量范围

您也可以这样做:-

include 'page1.php';

class Test {

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

}

$testObj = new Test;
print_r($testObj->test1());
a、 php

您可以包括上面的页面和
在你们班:

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 ) 

page2.php
上包含
page1.php
,使用全局范围变量并不是真正的OOP风格。我建议改为使用类属性或常量。@Roopendra:但无法访问类内的$conn。请给我你的答案。为什么它们必须在不同的页面上?包含或要求它,或在page2.php中声明变量。请阅读该命令。@deepus:您想要这个吗?
Array ( [0] => 1 [1] => 2 [2] => 3 )