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?
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:
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
$User = new User;
echo $User->color;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.