Trying to understand what is namespaces: Fatal error: Uncaught Error: Class 'feline\Cat' not found in C:\Users\bird\

Trying to understand what is namespaces: Fatal error: Uncaught Error: Class 'feline\Cat' not found in C:\Users\bird\

试图了解什么是名称空间、使用它们的意义、在哪里使用它们以及如何使用它们..

代码:

<?php 
namespace foo;

class Cat {
    static function says() {echo 'meoow';}  
} 

namespace bar;
class Dog {
    static function says() {echo 'ruff';}  
} 

namespace animate;
class Animal {
    static function breathes() {echo 'air';}  
} 


use foo as feline;
use bar as canine;
use animate;

echo \feline\Cat::says(), "<br />\n";
echo \canine\Dog::says(), "<br />\n";
echo \animate\Animal::breathes(), "<br />\n"; 

?>

获取错误:

Fatal error: Uncaught Error: Class 'feline\Cat' not found in C:\Users\bird\

您的错误是由您的第一个反斜杠引起的:

echo \feline\Cat::says(), "<br />\n";
echo \canine\Dog::says(), "<br />\n";
echo \animate\Animal::breathes(), "<br />\n"; 

改成:

echo feline\Cat::says(), "<br />\n";
echo canine\Dog::says(), "<br />\n";
echo animate\Animal::breathes(), "<br />\n";

它应该可以修复您的错误

什么是命名空间? 命名空间是封装项目的方式。

为什么要命名空间? 使用 OOP(面向对象编程)构建您的应用程序是必经之路,您不需要每次都重新编写代码,因为您可以重复使用您的代码,这就是命名空间可以在没有任何名称冲突的情况下做到的.

这里是 post 解释你的问题 - What are namespaces?

有关如何使用它们的示例 这里有一些示例和教程,您可以按照这些示例和教程更好地理解它。 - https://www.geeksforgeeks.org/php-namespace/ - https://www.php.net/manual/en/language.namespaces.rationale.php

如果你想学习php和OOP的使用我推荐你使用Laravel。 https://www.laravel.com