我还没有掌握 extract() 函数和传输变量的窍门。 我在用户 Controller 中有一个方法,其中定义了一些变量,并以数组形式发送到父 Controller 中的 View 函数,其中提取了数组。然后需要 View 。但是变量结果未定义。虽然可以打印数组内容。
这是具有简化配置文件功能的用户 Controller :
class User extends Controller{
public function profile(){
$profiledetails = $this->profiledetails();
$profilestatus = $this->profileStatus();
$this->view('profile', [$profiledetails, $profilestatus]);
}}
变量被发送到父 Controller 中的 View 函数:
class Controller {
public function view($view, $variables =[]){
extract($variables);
require_once './app/views/' . $view . '.php';
}}
并且在 View “profile.php”中,显示了 undefined variable 错误。我认为“extract()”函数将使 $profiledetails 和 $profilestatus 在 View 中作为变量可用。 我究竟做错了什么?也许我使用了错误类型的数组,或者我应该使用“可变变量”或其他东西……(在那种情况下,如何?)。
最佳答案
extract
使用关联数组。
$this->view('profile',
[
'profiledetails' => $profiledetails,
'profilestatus' => $profilestatus
]);
关于php - 使用 extract($variables) 获取内容,但变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30552397/