0
1

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.

【3行クイズ】クラス定義やrequire関数で正常かエラーかよく分からなくなるかもしれないクイズ

Posted at

はじめに

5つのソースコード(Q01~05)が、○(正常終了)か× (エラー)か答えてください。回答はページ末尾にあります。なお、動作確認したPHPのバージョンは7.2.17です。

※base.phpは共通して下記のソースになります。

base.php
<?php
class base{}

それでは、問題です。

Q.01

q01.php
<?php
new hoge();
class hoge extends base{}
class base{}

Q.02

q02.php
<?php
new hoge();
class base{}
class hoge extends base{}

Q.03

q03.php
<?php
new hoge();
require("base.php");
class hoge extends base{}

Q.04

q04.php
<?php
require("base.php");
new hoge();
class hoge extends base{}

Q.05

q05.php
require("base.php");
class hoge extends base{}
new hoge();

(回答の前に)結論

「ロード(includeやrequire) → 親クラス定義、子クラス定義(extendsやtrait) → インスタンス化 」という順番を守っていれば何の問題にはなりません。とある理由でバラしていたところ当たり前なことがよく分からなくなりました。私と同じように「わけが解らなくなる人」がいるのではないかと思いクイズにしてみました。

みなさんは、一瞬で答えられたでしょうか?

回答

  1. × エラー
  2. ○ 正常終了
  3. × エラー
  4. × エラー
  5. ○ 正常終了

参考リンク

0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?