dongyun4010
2013-10-10 14:54 阅读 120
已采纳

访问另一个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 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;
    
    点赞 评论 复制链接分享
  • doushihu5475 doushihu5475 2013-10-10 14:58

    PHP for File livesearch.php :

     require_once("../classes/User.php");
    
     $user = new User;
     echo $user->color;
    
    点赞 评论 复制链接分享
  • dsa2c2255888 dsa2c2255888 2013-10-10 15:04

    you should to use singleton of design patterns for speed. I do not recommend such a usage in this case. ( this->color instead user::color ).

    research design pattern, polymorphism.

    answer

    • userclass.php class User { public $color = "green"; }

    $User = new User;

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

    echo $User->color;

    点赞 评论 复制链接分享

相关推荐