SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    Patience... bronze trophy solidcodes's Avatar
    Join Date
    Jul 2006
    Location
    Philippines
    Posts
    936
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    Arrow OOP5 question which is correct?

    This is an instantiation question.

    notice the two ways to intantiate an object,

    Code:
    $human1 = new person();
    $human2 = new person;
    I tested them both and they work very fine.

    I don't understand why there are two ways to instantiate and object.

    Why is this?

    can someone please explain.

    Thank you in advance.

  2. #2
    SitePoint Wizard cranial-bore's Avatar
    Join Date
    Jan 2002
    Location
    Australia
    Posts
    2,634
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If the class has a constructor with arguments, you'll need to use the parenthesis and pass in the required arguments. Otherwise the second format is fine.

    e.g
    PHP Code:
    class user
    {
        protected 
    $userID;

        public function 
    __construct($userID) {
           
    $this->userID = (int)$userID;
        }

        public function 
    get_info() {
           
    $query "SELECT * FROM users WHERE userID = " $this->userID;
           
    //execute, return
        
    }
    }

    $user = new user(1673);    //pass a userID to the constructor
    $data $user->get_info(); 
    Personally I always use the first format.

  3. #3
    Patience... bronze trophy solidcodes's Avatar
    Join Date
    Jul 2006
    Location
    Philippines
    Posts
    936
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Thank you cranial-borne

    That is a good memory refresh for me.

    Thank you.

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Both are technically valid, but the form without parens is fairly uncommon. The norm is to write the parens even when there are no arguments. Note that it's also the norm to write class names with a capital first letter.


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
  •