1

クラスとして別のphpファイルの変数を使用したい。しかし、常にエラーが発生します: Notice: Undefined variable:...

最初: ユーザー オブジェクトを作成します。 ファイル: 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");

ファイル: User.php

class User
{
   public $color = "green";
}

ファイル livesearch.php

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

echo $User->color;

私は index.php ファイルでクラス user からオブジェクトを作成します。そこでも User.php ファイルに一度必要としますが、それは機能します。クラスの変数にアクセスできないのはなぜですか?

4

3 に答える 3

4

PHP の変数名は大文字と小文字を区別します。

echo $User->color;

する必要があります

echo $user->color;

また、次の場合を除きlivesearch.php、変数にアクセスできません。index.php

  • に含まれていindex.phpます。その場合、index.php含まれる前に割り当てられたすべての変数にアクセスできます。
  • livesearch.php含まれていindex.phpます。その場合、含まれindex.phpているポイントの後に割り当てられたすべての変数にアクセスできますindex.php

例えば。あなたのファイルですが、わずかに変更されています:

ファイル: index.php

// load the user class
require_once("User.php");

$user = new User();

include("livesearch.php");

ファイル: User.php

class User
{
   public $color = "green";
}

ファイル: livesearch.php

echo $User->color;

書くのと同じです:

// From User.php
class User
{
   public $color = "green";
}

// From index.php
$user = new User();

// From livesearch.php
echo $User->color;
于 2013-10-10T14:58:08.417 に答える
0

速度のために設計パターンのシングルトンを使用する必要があります。この場合、このような使用法はお勧めしません。( this->color 代わりに user::color )。

研究デザインパターン、ポリモーフィズム。

答え

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

$User = 新しいユーザー;

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

echo $User->color;

于 2013-10-10T15:04:21.073 に答える
0

ファイル livesearch.php の PHP :

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

 $user = new User;
 echo $user->color;
于 2013-10-10T14:58:52.783 に答える