[英]Access class variable in another PHP file
I want to use variables in another php file as the class. 我想在另一个php文件中使用变量作为类。 But I get always the error: Notice: Undefined variable:...
但我总是得到错误:注意:未定义的变量:...
First: I create a user object: File: index.php 第一:我创建了一个用户对象: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 文件:User.php
class User
{
public $color = "green";
}
File livesearch.php 文件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. 我在index.php文件中从类用户创建了一个对象,我在User.php文件中使用了一次需要一次并且它可以工作。 Why I cant access the variable of the class?
为什么我无法访问类的变量?
Variable names in PHP are case sensitive: PHP中的变量名称区分大小写:
echo $User->color;
should be 应该
echo $user->color;
Also the livesearch.php
doesn't have access to the variables in index.php
unless: 此外,
livesearch.php
无法访问index.php
的变量,除非:
index.php
. index.php
。 In which case it has access to all the variables assigned in index.php
before it was included. index.php
中包含的所有变量。 livesearch.php
includes index.php
. livesearch.php
包含index.php
。 In which case it has access to all the variables assigned in index.php
after the point where index.php
was included. index.php
中包含index.php
之后指定的所有变量。 eg. 例如。 Your files, but slightly modified:
你的文件,但略有修改:
File: index.php 文件:index.php
// load the user class
require_once("User.php");
$user = new User();
include("livesearch.php");
File: User.php 文件:User.php
class User
{
public $color = "green";
}
File: livesearch.php 文件: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 : 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 ).
(this-> color而不是user :: color)。
research design pattern, polymorphism. 研究设计模式,多态性。
answer 回答
$User = new User; $ User =新用户;
echo $User->color; echo $ User-> color;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.