2014-07-19 44 views
0

當我包含一個php文件/類時,我想獲得類/包含變量/元素,不知怎的,也許我應該嘗試反射來做到這一點?如果是這樣,怎麼樣?
舉例來說,我有一個PHP類調用foo.php:如何在包含php的過程中獲取包含的元素?

<?php 
class foo 
{ 
    public function bar() 
    { 
     return "foobar"; 
    } 
} 
?> 

然後,在bar.php,我想:

<?php 
class bar 
{ 
    public function foo() 
    { 
     $included_resources = include("foo.php"); // Notice, $included_resources is an array 
     if (($key = array_search("foo", $included_resources)) != false) // "foo" can be any variable or class name 
      return $included_resources[$key]->bar(); 
    } 
} 
$helloworld = new bar(); 
echo $helloworld->foo(); 
?> 

結果:一個字符串值將在屏幕上顯示「foobar」

+3

進一步解釋。 –

回答

1

首先,在包含文件之前將聲明的變量存儲在數組中。然後做包括。然後再將聲明的變量存儲在另一個數組中。然後,只需檢查區別:

$declared_vars_before = get_defined_vars(); 
include 'another_file.php'; 
$declared_vars_after = get_defined_vars(); 
foreach ($declared_vars_after as $value) { 
    if (!in_array($value, $defined_vars_before)) { 
    echo $value . '<br>'; 
    } 
} 

與類相同,但使用get_declared_classes而不是get_defined_vars。

相關問題