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

访问另一个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?

我想在另一个php文件中使用变量作为类。 但我总是得到错误:注意:未定义的变量:... p>

首先:我创建一个用户对象: File:index.php p>

 &lt;?php 
 
 //包括db connection 
require_once(“config / config.php”)的配置/常量; 
 
 //加载用户类
require_once(“classes  /User.php");
nnuseruser = new User(); 
 
include(“views / order.php”); 
  code>  pre> 
 
 

文件:User.php p>

  class User 
 {
 public $ color =“green”; 
} 
  code>  pre> 
 \  n 

文件livesearch.php p>

  require_once(“../ classes / User.php”); 
 
echo $ User-&gt; color; 
   pre> 
 
 

我在index.php文件中从类用户创建一个对象,我在User.php文件中也使用了一次,并且它可以工作。 为什么我无法访问类的变量? p> div>

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;

PHP for File livesearch.php :

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

 $user = new User;
 echo $user->color;

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;