2つのUserクラスがあり、1つは/model/User.phpにあり、もう1つは/assets/User.phpにあります。
ここで、/ model / User.phpからUserクラスを拡張するクラスが必要ですが、phpは常に/assets/User.phpにあるクラスを探しているようです。phpがどのクラスから拡張するかをどのように決定するのか、何か考えはありますか?
名前空間を使用する
user.php
:
class User {
function someMethod(){}
}
myUser.php
:
namespace My;
class User {
function someMethod(){}
}
そして、次のように使用できます。
include 'user.php';
include 'myuser.php';
$user1 = new User();
$user2 = new \My\User();
名前空間を使用できます:PHPマニュアル
(使用する場合) spl_autoload_register 関数 ( http://php.net/manual/en/function.spl-autoload-register.php ) を適切にセットアップして、同じ名前のファイル内のオブジェクトを自動ロードできるようにする必要があります。のオブジェクトは同じにすることはできません。
オブジェクトは、ファイルが保存されている名前とパスで区別できます。
たとえば、bootstrap.php でコア クラスを必要とし、オートローディング関数を定義します。
<?php // bootstrap.php
require_once Core.php;
spl_autoload_register(array('Core', 'auto_load'));
$myUserClass = new MyClasses_User() // the required files for the class are loaded because of auto_load, PHP determines the right classes due to naming conventions: DirName_ClassName
?>
<?php // Core.php
define('DIR_SEPARATOR', '/');
class Core {
// Autoloading
public static function auto_load($class, $dir_classes = 'classes')
{
$file = str_replace('_', DIR_SEPARATOR, $class); // replace _ by / for path to file
if ($path = find_file_based_on_class_name($dir_classes, $file))
{
// Load the class file
require $path;
}
}
?>
<?php
// classes/Model/User.php
class Model_User {
// define the class
}
?>
// classes/Assets/User.php
<?php
class Assets_User {
// define the class
}
?>
// classes/MyClasses/User.php
<?php
class MyClasses_User exdends Model_User {
// define the class
}
?>