SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2012
    Posts
    99
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    question about instantiateing classes with namespaces

    Hey all,

    I have started to look into namespaces. I really do like them! I am just having trouble understanding how they are instantiated. before namespaces to start a class I would do something like

    PHP Code:

    $foo 
    = new bar(); 
    but with namespaces I should be able to do something like this correct?

    PHP Code:

    $foo 
    = new \Core\bar(); 
    Thanks for the help! I just have to wrap my head around it haha

  2. #2
    SitePoint Zealot
    Join Date
    Feb 2005
    Location
    Aveiro, Portugal
    Posts
    164
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Hi!
    Check out this thread: link.

    I think it answers your qustion.

    HTH
    Yours truely
    Mário Ramos

  3. #3
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    426
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You may find this helpful: http://php.net/manual/en/language.namespaces.rules.php

    I like to think of it like a file directory so changing namespace is like changing directory; you can always reference the current directory or an absolute path from the root.

    I must admit, I find it easier to just use a fully qualified namespace to access anything outside of the current namespace. It's a bit of a pain that any use declarations only apply to the current file. For this reason, if you ever had to move a class to a different namespace, it could be a bit of a pain.

    If you use the PSR-0 standard instantiating an object would look like:

    PHP Code:
    $object = new \Vendor\Package\Class($foo); 

  4. #4
    Non-Member
    Join Date
    Oct 2007
    Posts
    363
    Mentioned
    11 Post(s)
    Tagged
    0 Thread(s)
    Check out this free video that explains php namespaces quite well: http://knpuniversity.com/screencast/...in-120-seconds


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •