0

Trying to understand what is namespaces, and what is point of using them, and where to use them, and how to use them..

Code:

<?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"; 

?>

Getting error:

Fatal error: Uncaught Error: Class 'feline\Cat' not found in C:\Users\bird\
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
user1942505
  • 480
  • 5
  • 11
  • 20

1 Answers1

1

Your error is caused by your first backslashses at:

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

change it into:

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

and it should fix your error

What are namespaces ? Namespaces are the way of encapsulating items.

Why namespaces? Building your application with OOP ( object-orientated programming ) is the way to go, you don't need to re-write your code every single time because you can re-use your code, this is what namespaces can do without any name conflicts.

Here is the post that explains your question - What are namespaces?

Examples on how to use them Here are a few examples and tutorials you can follow to understand it better. - https://www.geeksforgeeks.org/php-namespace/ - https://www.php.net/manual/en/language.namespaces.rationale.php

If you want to learn php and the use of OOP I recommend you to use Laravel. https://www.laravel.com

Wesley
  • 61
  • 10