Help us understand the problem. What is going on with this article?

PHPの__autoload関数の小さなサンプル

More than 1 year has passed since last update.
test.php
<?php

$user = new User("kure");
echo $user->getName();

User.class.php
<?php
class User{
    private $name;
    public function __construct(string $name){
        $this->name = $name;
    }

    public function getName(){
        return $this->name;
    }
}

以上の場合、クラスのファイル(User.class.php)が読み込まれずに、以下のエラーが出る

PHP Fatal error:  Uncaught Error: Class 'User' not found in 

以下のように __autoload 関数を定義すれば、ファイル名を追って読み込まれる。関数の引数$nameにはインスタンス化しようとしたクラス名が渡される。

test.php
<?php

function __autoload($name){
    $filename = $name.".class.php";
    require $filename;
}

$user = new User("kure");
echo $user->getName();

kure
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした