Archived video

This video is archived and won't be updated. We're keeping it online for now as a courtesy.

Alternate resources: 

PHP Namespaces in 120 Seconds

Video loading...

  • 0:15
    PHP Namespaces in 120 Seconds Leanna Pelham
  • 0:27
    Time to master PHP 5.3 Namespaces.
  • 0:31
    The good news is Namespaces are easy.
  • 0:34
    To prove it, we've challenged ourselves
  • 0:35
    to explain them in 120 seconds.
  • 0:38
    Let's go.
  • 0:39
    Meet Foo.
  • 0:40
    He's a PHP 5.2 class that does a lot of important things.
  • 0:45
    Foo, say hi to the listener.
  • 0:47
    OK, so Foo's humor is a bit old, too.
  • 0:50
    Using Foo is easy.
  • 0:51
    Simply, "new Foo."
  • 0:53
    To keep up with the times, let's put Foo
  • 0:55
    in a brand new PHP 5.3 Namespace.
  • 0:58
    A Namespace is like a directory, and by adding Namespace,
  • 1:01
    Foo now lives in Acme\Tools.
  • 1:04
    to use Foo, we call him by his fancy new name.
  • 1:07
    This is just like referring to a file with its absolute path.
  • 1:11
    And that's really it.
  • 1:13
    Adding a Namespace to a class is like organizing files from one
  • 1:16
    directory into a bunch of subdirectories.
  • 1:18
    To refer to a class, use its fully qualified name
  • 1:21
    starting with the slash.
  • 1:23
    From here, it's all gravy.
  • 1:25
    Since running around with this giant name is a drag,
  • 1:28
    let's add a shortcut.
  • 1:30
    The use statement lets us call \Acme\Tools\Foo class by a nickname.
  • 1:38
    Heck, we can call it anything, or just let it default to Foo.
  • 1:42
    Great, but what about old school, non-Namespace PHP classes?
  • 1:46
    For that, let's pick on DateTime, a handy class that's core to PHP
  • 1:50
    and got some new bells and whistles in PHP 5.3.
  • 1:54
    Forever and ever, creating a new DateTime object
  • 1:56
    looked the same-- new DateTime And if we're in a normal file,
  • 2:01
    this still works.
  • 2:02
    But in a Namespace file, PHP thinks you're
  • 2:04
    talking about a class in the Acme\Tools Namespace.
  • 2:08
    You can either refer to the class by its fully qualified name,
  • 2:11
    \DateTime, or add a use statement.
  • 2:20
    Yes, the use statement looks silly, but it tells PHP
  • 2:22
    that when you say DateTime, you mean the non-Namespace class DateTime.
  • 2:27
    Oh, and get rid of the beginning slash with the use statement.
  • 2:30
    Everything works completely the same with or without it,
  • 2:33
    but you typically don't see it.
  • 2:35
    OK, bye.

PHP Namespaces in 120 Seconds

Loading...

Still not quite comfortable with PHP 5.3 namespaces? No problem! Give us 120 seconds and we'll introduce you to all the crazy characters ("namespace", "use" and "\") and show you how they work.

Additional resources: