dongyun4010 2013-10-10 14:54
浏览 129
已采纳

访问另一个PHP文件中的类变量

I want to use variables in another php file as the class. But I get always the error: Notice: Undefined variable:...

First: I create a user object: File: index.php

<?php

// include the configs / constants for the db connection
require_once("config/config.php");

// load the user class
require_once("classes/User.php");

$user = new User();

include("views/order.php");

File: User.php

class User
{
   public $color = "green";
}

File livesearch.php

require_once("../classes/User.php");

echo $User->color;

I create an object from the class user in a index.php file, I use there also a require once to the User.php file and it works. Why I cant access the variable of the class?

  • 写回答

3条回答 默认 最新

  • duancong7358 2013-10-10 14:58
    关注

    Variable names in PHP are case sensitive:

    echo $User->color;
    

    should be

    echo $user->color;
    

    Also the livesearch.php doesn't have access to the variables in index.php unless:

    • It is includes in index.php. In which case it has access to all the variables assigned in index.php before it was included.
    • livesearch.php includes index.php. In which case it has access to all the variables assigned in index.php after the point where index.php was included.

    eg. Your files, but slightly modified:

    File: index.php

    // load the user class
    require_once("User.php");
    
    $user = new User();
    
    include("livesearch.php");
    

    File: User.php

    class User
    {
       public $color = "green";
    }
    

    File: livesearch.php

    echo $User->color;
    

    Is the same as writing:

    // From User.php
    class User
    {
       public $color = "green";
    }
    
    // From index.php
    $user = new User();
    
    // From livesearch.php
    echo $User->color;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料