0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at
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();

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?