0

如何使类属性可用于同一类方法中的其他包含文件?

// file A.php
class A
{
    private $var = 1;

    public function go()
    {
        include('another.php');
    }
}

在另一个文件中:

// this is another.php file
// how can I access class A->var?
echo $var; // this can't be right

考虑到范围,这是否可能。如果 var 是一个数组,那么我们可以使用 extract,但如果 var 不是,我们可以将它包装在一个数组中。有没有更好的方法

谢谢!

编辑

好的,澄清another.php实际上是另一个文件。基本上,在上面的示例中,我们有 2 个文件A.php包含类 A 和another.php,它是另一个执行某些操作的文件/脚本。

回答:我的错...我从 index.php 中包含了另一个.php .. 我看到范围仍然适用.. 谢谢大家..

4

3 回答 3

1

您的问题似乎是,“当在方法中包含的文件中,我如何访问私有实例成员? ”对吗?

在您的示例代码中,您在方法中包含一个文件。

方法只是函数。与 PHP 的所有其他领域一样,被包含的文件将继承整个当前范围。这意味着 include 可以看到该方法中范围内的所有内容。包括$this.

换句话说,您将访问包含文件中的属性,就像您从函数本身内部访问它一样,如$this->var.


例如,使用 PHP 交互式 shell:

[charles@lobotomy /tmp]$ cat test.php
<?php
echo $this->var, "\n";

[charles@lobotomy /tmp]$ php -a
Interactive shell

php > class Test2 { private $var; public function __construct($x) { $this->var = $x; } public function go() { include './test.php'; } }
php > $t = new Test2('Hello, world!');
php > $t->go();
Hello, world!
php > exit
[charles@lobotomy /tmp]$ php --version
PHP 5.4.4 (cli) (built: Jun 14 2012 18:31:18)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
    with Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans
于 2012-12-08T05:16:39.433 回答
0

您已定义为私有,$var意味着$var只能由成员函数访问。如果你需要访问,要么将其公开,要么从成员函数中返回。您应该阅读PHP 手册中有关可见性的更多信息$var

编辑:使您的情况有趣的是您是include从成员函数调用的。 include将继承调用它的范围。因此,从技术上讲,您可以$this->varanother.php. 但是,我强烈反对这种做法。如果another.php包含在其他任何地方,您将收到错误。请,不要这样做。这是糟糕的编程习惯。

如果你真的必须,将这些行添加到A.php

$obj = new A();
$obj->go();    // this will call another.php, which will echo "$this->var"

然后改成another.php这样:

echo $this->var;

它会起作用;你会得到正确的输出。请注意,如果您不声明 A 类的实例,这将失败(例如,A::go()A->go()等都将失败)。这是在 PHP 中处理事情的一种糟糕的方式。

但是以更好的方式做事,您可以将变量公开:

class A {
    public $var = 1;  //note, it is public!
    public function go() {
        include('another.php');
    }
}
$obj = new A();
echo $obj->var; //woot!

或者,保持私有(这是更好的 OOP):

class A {
    private $var = 1;  //note, it is private

    //make a public function that returns var:
    public function getVar() {
        return $this->var;
    }

    public function go() {
        include('another.php');
    }
}

$obj = new A();
echo $obj->getVar(); //woot!
于 2012-12-08T05:10:15.750 回答
-2
 class A
{
    public $var = 1;

    public function go()
    {
        include('another.php');
    }
}

$objA = new A();

$objA->go();
于 2012-12-08T05:15:19.700 回答