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条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错