PHP对象(不是类)在另一个类中不可用

时间:2015-07-27 14:11:47

标签: php object scope

我读到对象(类的实例化)是全局范围的。这是有道理的,因为对象(同样,我不是在讨论类)应该很容易在代码的其他部分重用。但似乎这些信息是错误的。看看这个例子:

<?php

class test {
    public $returnvalue = "foobar";
}

$testobject = new test();


class getvalue {

    private $var;

    function printvalue() {
            $var = $testobject->returnvalue;
            print "$var";
    }

}

$getvalueobject = new getvalue();
$getvalueobject->printvalue();

?>

此代码返回错误:

  

尝试在...中获取非对象的属性

那么,在getvalue类中可以使$ testobject(类“test”的实例化)可用吗?

提前致谢。

3 个答案:

答案 0 :(得分:0)

<?php

class test {
    public $returnvalue = "foobar";
}

//$testobject = new test(); MOVE INTO METHOD


class getvalue {

    private $var;

    function printvalue() {
            $testobject = new test(); //For instance here
            $var = $testobject->returnvalue;
            print "$var";
    }

}

$getvalueobject = new getvalue();
$getvalueobject->printvalue();

?>

以下是文档:http://php.net/manual/en/language.variables.scope.php

答案 1 :(得分:0)

<?php

class test {
    public $returnvalue = "foobar";
}

$testobject = new test();


class getvalue {

    public $classObject;

    function printvalue() {
        $var = $this->classObject->returnvalue;
        print "$var";
    }

}

$getvalueobject = new getvalue();
$getvalueobject->classObject = $testobject;
$getvalueobject->printvalue();

?>

类扩展的示例

<?php

class test {
    public $returnvalue = "foobar";
}

// If you use extends in PHP classes you can access all variables and methods from the base class (In this example the base class would be Test)
class getvalue extends test {
    function printvalue() {
        // Because we extended the base class Test, we can access it's public variable returnvalue
        $var = $this->returnvalue;
        print "$var";
    }

}

$getvalueobject = new getvalue();
$getvalueobject->printvalue();

?>

答案 2 :(得分:0)

我错了。对象没有全局范围。

因此,如果你需要在另一个类中使用一个对象,那么你必须将它传递给__construct函数并将该对象存储在类属性中,或者你必须将它传递给使用它的函数:

<?php

class test {
    public $returnvalue = "foobar";
}

$testobject = new test();


class getvalue {

    private $var;
    private $testobject;

    function __construct($testobject) {
        $this->testobject = $testobject;
    }

    function printvalue() {
        $var = $this->testobject->returnvalue;
        print "$var";
    }

}

$getvalueobject = new getvalue($testobject);
$getvalueobject->printvalue();

?>

<?php

class test {
    public $returnvalue = "foobar";
}

$testobject = new test();


class getvalue {

    private $var;

    function printvalue($testobject) {
        $var = $testobject->returnvalue;
        print "$var";
    }

}

$getvalueobject = new getvalue();
$getvalueobject->printvalue($testobject);

?>