[英]Access property from include inside a class method in PHP
你如何讓一個類的屬性可用於同一類的方法里面包含的其他文件?
// 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。我看到范圍仍然適用..謝謝大家..
您的問題似乎是,“ 在方法中包含的文件中時,如何訪問私有實例成員? ”對嗎?
在示例代碼中,您將在方法內包含一個文件。
方法只是功能。 與PHP的所有其他區域一樣,包含的文件將繼承整個當前scope 。 這意味着,包括看到的范圍,該方法的一切。 包括$this
。
換句話說,在包含文件中,就像你從函數本身內部訪問它,因為你會訪問屬性$this->var
。
例如,使用交互式PHP殼:
[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
您已將$var
定義為private,這意味着$var
只能由成員函數訪問。 如果您需要訪問$var
,則將其公開,或從成員函數返回。 您應該從PHP手冊中閱讀有關可見性的更多信息。
編輯:使您的情況有趣的是,您正在從成員函數調用include
。 include
將繼承調用它的范圍。 因此,從技術上講,您可以從another.php
調用$this->var
。 但是,我強烈反對這種做法 。 如果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事情的一種可怕方法。
但是,做一個更好的方法,您可以將變量設為public:
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!
class A
{
public $var = 1;
public function go()
{
include('another.php');
}
}
$objA = new A();
$objA->go();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.