🚀 تخفیف ۳۵٪ + ۳.۵ میلیون هدیه! برنامه‌نویسی رو الان شروع کن - فقط امروز!
۰ ثانیه
۰ دقیقه
۰ ساعت
۴ Hossein S
Autholodin error
جامعه پی اچ پی ایجاد شده در ۱۳ تیر ۱۴۰۲

سلام دقیقه ۳۵ اونجای که نیم اسپیس اضافه شد دیگه اتو لودر من کار نمیکنه

Person.php

 namespace App\\Classes;
 class Person {
     private  $name;
     public function __construct()
     {
         $this->name = static::class . "-" . rand(100 , 999);
     }
     public function sayHello()
     {
         echo "Hello, my name is " . $this->name . PHP_OS . PHP_EOL;
     }
 }
-----------------------------------------------------------------------------------------------------------------
main.php

include "autoload.php";
// include "Person.php";
// include "Student.php";
// include "Teacher.php";
$p1 = new App\\Classes\\Person();
$p1->sayHello();
$s1 = new App\\Classes\\Student();
$s1->sayHello();
$t1 = new App\\Classes\\Teacher();
$t1->sayHello();
-----------------------------------------------------------------------------------------------------------------
autoloader.php

function my_autoloader($class)
{
    $classFile = __DIR__ . "/$class.php";
     if (file_exists($classFile) && is_readable($classFile)){
         include $classFile;
        //  echo 'from autoload my_autoloader =>' . $class . ' used ' . PHP_EOL;
     }else{
         echo ("Could not find class  $classFile");
     }
}
spl_autoload_register('my_autoloader');

این هم متن خطای که به من میده

Could not find class /var/www/html/OOP/autholoading/App\\Classes\\Person.php
Fatal error: Uncaught Error: Class "App\\Classes\\Person" not found in /var/www/html/OOP/autholoading/main.php:7 Stack trace: #0 {main} thrown in /var/www/html/OOP/autholoading/main.php on line 7

سلام حسین جان، فانکشنتون رو به شکل زیر اصلاح کنین:


function my_autoloader($class)
{
    $classFile = __DIR__ . '/' . str_replace('\\\\', '/', $class) . '.php';
    if (file_exists($classFile) && is_readable($classFile)) {
        include $classFile;
    } else {
        echo "Could not find class $class";
    }
}
صادق برزگر ۱۳ تیر ۱۴۰۲، ۱۱:۰۳

مرسی ممنون مشکلم حل شد میشه محبت کنی یه توضیح مختصر که دلیلش چی بود؟ممنون میشم اقای برزگر

Hossein S ۱۳ تیر ۱۴۰۲، ۱۲:۱۲

خواهش میکنم حسین جان، وقتی از Namespace‌ها استفاده میکنیم، فایل کلاس رو که میخواد include کنه همراه با نیم اسپیس هست و در نیم اسپیس‌ها از \\ برای جداسازی استفاده میشه که در فانکشن اتولود اومدیم این کاراکتر \\ رو تبدیل به / کردیم تا آدرس فایل تصحیح بشه و بدرستی لود بشه.

بهترین پاسخ
صادق برزگر ۱۳ تیر ۱۴۰۲، ۱۲:۴۹

مرس این بخاطر سیتم عاملم بود

Hossein S ۱۳ تیر ۱۴۰۲، ۱۲:۵۵