Apa itu namespace di php?
I've an idea! Let's master PHP namespaces... and let's do it in under 5 minutes. Sip some coffee... let's go! Show Meet FooMeet
Say hi
To instantiate our favorite new class, I'll move over to a different file and say - drumroll -
Tada! We can even call a method on it:
Will it work? Of course! I can open a terminal and run: Namespaces: Making Foo more HipsterRight now,
Usually the namespace of a class matches its directory, but that's not technically required. I just invented this one! Using a Namespaced ClassCongratulations! Our friend
just like you can use the absolute path to reference a file in your filesystem: When we try the script now: It still works! The Magical & Optional use StatementAnd... that's really! Namespaces are basically a way to... make your class names longer! Add the namespace... then refer to the class using the namespace plus the class name. That's it. But... having these long class names right in the middle of your code is a bummer! To fix that, PHP namespaces have one more special thing: the
This creates a... sort of... "shortcut". Anywhere else in this file, we can now just type
and PHP will know that we're really referring to the long class name: Or... if you leave off the
So, namespaces make class names longer... and Core PHP ClassesIn modern PHP code, pretty much all classes you deal with will live in a namespace... except for core PHP classes. Yep, core PHP classes do not live in a namespace... which kinda means that they live at the "root" namespace - like a file at the root of your filesystem: Let's play with the
core
When we run the script: It works perfectly! But... now move that same code into the
Now try the code: Ah! It explodes! And check out that error!
The real class name should just be
There are two ways to fix this. The
first is to use the "fully qualified" class name. So,
Yep... that works just like a filesystem. Or... you can use
That's really the same thing: there's no And... we're done! Namespaces make your class names longer, use statements allow you to create "shortcuts" so you can use short names in your code and the whole system works exactly like files inside directories. Have fun! Jelaskan apa fungsi namespace?Apa Fungsi Dari Namespace? .NET menggunakan namespace sebagai cara untuk memisahkan file-file class kedalam kategori yang terkait (mengorganisir cakupan kategori). Selain itu, penggunaan namespace juga bisa membantu menghindari bentroknya penamaan dalam aplikasi yang mungkin berisi beberapa class dengan nama yang sama.
Apa itu namespace pada OOP dalam bahasa PHP?Namespaces PHP
Namespaces adalah kualifikasi yang menyelesaikan dua masalah berbeda, yaitu: Mereka memungkinkan pengorganisasian yang lebih baik dengan mengelompokkan kelas-kelas yang bekerja sama untuk melakukan tugas. Mereka memungkinkan nama yang sama digunakan untuk lebih dari satu kelas.
|