Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?

More than 3 years have passed since last update.

@kure

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

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
Help us understand the problem. What is going on with this article?
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
0
Help us understand the problem. What is going on with this article?