LoginSignup
2024_Hello_World
@2024_Hello_World

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

名前空間の使い方について PHP

Q&AClosed

解決したいこと

名前空間を使い他ファイルで定義したクラスを参照したいです。
(Str.phpで定義したStrクラスをStringUtils.phpで参照)
mb_string関数を使いkkkをKKKに変換したいです。

発生している問題・エラー

Fatal error: Uncaught Error: Class "Illuminate\Support\Str" not found in C:\xampp\htdocs\php_practice\StringUtils.php:10 Stack trace: #0 

該当するソースコード

Str.php
<?php

namespace Illuminate\Support;

class Str
{
    public static function upper(string $value):string
    {
        return mb_strtoupper($value, 'UTF-8');
    }
}
StringUtils.php
<?php

namespace App\Utils;
use Illuminate\Support\Str;

class StringUtils
{
    public static function upperCase(string $value):string
    {
        return Str::upper($value);
    }
};

$result = StringUtils::upperCase("kkk");
echo $result;
0

2Answer

Illuminate\SupportはLaravelフレームワークの名前空間ですが、そこから抜き出して独自に作成されたものと推測して回答します。

他のPHPファイルのデータや機能を参照するには、事前に対象のPHPファイルが読み込まれている必要があります。requireincludeを使ってStr.phpを読み込みましょう。

2Like

Comments

  1. requireを使い読み込むことができました。
    ありがとうございました!

php の ドキュメントの 名前空間の使用法: エイリアス/インポート の note にある様に

The <?php use ?> statement does not load the class file. You have to do this with the <?php require ?> statement or by using an autoload function.

use は読み込みを行いません。 required や autoload を設定して読み込みを実施してください。
もしかしたら autoload が設定されていない可能性があります。

1Like

Comments

  1. requireで読み込みできました!
    autoloadの知識がないので勉強してみます。
    ご回答いただきありがとうございました!

Your answer might help someone💌