Page 1 of 2 12 Last
  • Jump to page:
    #1
  1. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171

    Calling methods in class


    Hi is there any difference between these 2? Which one is prefered?
    1 -
    PHP Code:
    $this->getView()->display($model); 
    2 -
    PHP Code:
    $view $this->getView();
    $view->display($model); 
    Bad hitler
  2. #2
  3. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    It doesn't matter.



    Originally Posted by English Breakfast Tea
    Bad hitler
    What?
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  4. #3
  5. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171
    Originally Posted by Jacques1
    It doesn't matter.





    What?
    schindler's list is on tv; that guy!!
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    158
    Rep Power
    11
    It doesn't matter.

    Only in as much as that the final result is the same.

    In rel life you have to conside more things, like the fact that in the first, chained, method, the getView() *MUST* return a view object or throw an exception, it cannot return anything otherthan a view, which means taht your call to the method must happen inside a try/catch. This seems logical for "getView()" because you don't expect it to return anything other than a view, but this is just one, very simple, example of the using a get...() method.

    I've seen people create superchained stuff like:
    $this->getView()->setColor(blue)->setHeight(100)->setFoo('bar');
    and claim that this is readable and maintainable. I guess that's a matter of opinion, but I find it hard to agree.

    Another thing to consider is dependencies and micro-ioptimizations. If you have to set four parameters in a view, do you want to hardcode the source of the view four times using $this->getView()? And do you want PHP to run the getview() function four times, knowing that the result is going to be the same all four times?

    Comments on this post

    • Jacques1 disagrees
  8. #5
  9. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by Vinny42
    In rel life you have to conside more things, like the fact that in the first, chained, method, the getView() *MUST* return a view object or throw an exception, it cannot return anything otherthan a view, which means taht your call to the method must happen inside a try/catch.
    Sorry, but this is nonsense. We already had a long discussion about this myth, but I can't find the thread right now.

    In object-oriented programming, a method is supposed to always return either a specific type or throw an exception. There is no "return false on error" or something like that. This practice is used in procedural programming as an alternative to exceptions (because procedural languages don't always have exceptions).

    Unfortunately, PHP itself often uses a weird mixture of procedural and object-oriented programming. So people have come to believe that they need to check every return value and see if it's false before they use it. No. You either get the expected type. Or the whole evaluation is cancelled, and you get a proper exception. There's no third possibility.

    This is why you can always safely chain method calls. If a call is successful, it's all fine. If the method call isn't successful, it's also fine, because you get an exception. Whether or not this exception was generated within a method chain is completely irrelevant.

    If a particular method actually doesn't allow chaining, then it's broken and needs to be fixed. For native PHP methods, that's very easy, because they usually have an option for turning on exceptions (see the PDO extension or MySQLi).

    Long story short: Do use method chaining. It works just fine, and it's one of the greatest features of OOP.



    Originally Posted by Vinny42
    I've seen people create superchained stuff like:
    $this->getView()->setColor(blue)->setHeight(100)->setFoo('bar');
    and claim that this is readable and maintainable. I guess that's a matter of opinion, but I find it hard to agree.
    Then I guess you simply aren't familiar with OOP.

    This technique is one of the basics of OOP. Without it, there would be no sane way of implementing query builders, for example.



    Originally Posted by Vinny42
    Another thing to consider is dependencies and micro-ioptimizations. If you have to set four parameters in a view, do you want to hardcode the source of the view four times using $this->getView()? And do you want PHP to run the getview() function four times, knowing that the result is going to be the same all four times?
    What? Are you arguing against calling getter methods?

    Trust me, none of the performance issues your application may have is caused by "too many getter calls". If you do experience bad performance, check your server architecture, use bytecode caching, check the database indexes, optimize your queries. But saving three getter calls has zero benefit.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    158
    Rep Power
    11
    Long story short: Do use method chaining. It works just fine, and it's one of the greatest features of OOP.

    This technique is one of the basics of OOP. Without it, there would be no sane way of implementing query builders, for example.

    What? Are you arguing against calling getter methods?

    none of the performance issues your application may have is caused by "too many getter calls

    Hmm.. reading taht, and thinking back to your reply in the the recent htmlpurifier topic I think it's best if I don't argue with you. You and I both have very strong opinions about matters and they are exactly opposites. We both have valid reasons for having them but I don't think either of us is goign to convince the other.

    I'd like to read that topic you mentioned though, hoping of course that it is fact based :-)
  12. #7
  13. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171
    Jacques would you please explain why you might need to create an object when the class does not exist?
    PHP Code:
    $object = new stdClass();
    $object->property 'Here we go'
    This is an instance of "nothing". What is the benefit of an object like this?

    Thanks
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by English Breakfast Tea
    What is the benefit of an object like this?
    It's simply a data container. It's the object-oriented equivalent of an associative array.

    Personally, I'd use an array. But the people who wrote this obviously wanted an object.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  16. #9
  17. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171
    Hi;

    When $this returns an empty object, how is it possible that I can access a method in that empty object?

    Question 1:
    How is that I can access method show() while print_r($this); returns an empty object with no method in it? I mention later what manual says.
    PHP Code:
    class {
            
        public function 
    test()
           {
              
    print_r($this);
              return 
    $this
           }
        public function 
    show()
            {
                echo 
    "HI";
            } 
    }

    $a = new a();

    print_r($a->test()->show());


    /*prints:
    a Object
    (
    )
    HI
    */ 

    Great in PHP5 methods can return objects, cool. That makes method chaining possible. Going a bit deeper in that takes me here to make a sense of return $this. When $this returns an empty object, how can I access a method in that empty object?

    Question 2:
    Related to above, why don't I see the method "test" in print_r? I thought when I instantiate I see all methods and properties as this is a blue print?

    I see the manual says:
    "In PHP 5 all public, private and protected properties of objects will be returned in the output."
    But why not methods? It doesn't make sense because I can access those methods via the instantiated object and those methods are also a part of that object.

    PHP Code:
    class {
            
        public 
    $val;
        public function 
    test()
           {
               
           }
    }

    $a = new a();
    print_r($a);

    /*prints:

    a Object
    (
        [val] => 
    )*/ 


    Question 3: And it overwrites the value of the property for the life of the script for ONLY THAT OBJECT!

    I thought if the property is static, the value changes everywhere in the script
    static property is a property that its value is shared between all objects
    So I expected the script below to print
    Ben, SaltSaltSalt
    but it prints
    Ben, SaltSaltdefault last name
    PHP Code:
    class {
            
        private 
    $name
        public static 
    $last_name 'default last name';    
        public function 
    name($name)
           {
              
    $this->name $name;
              return 
    $this
           }
        public function 
    lastName($last_name)
            {
                
    $this->last_name $last_name;
                return 
    $this;
            } 
        public function 
    show()
            {
                return 
    $this->name.", ".$this->last_name;     
            }    
    }

    $a = new a();

    echo 
    $val $a->name('Ben')->lastName('Salt')->show();
    echo 
    $a->last_name;


    $b = new a();
    echo 
    a::$last_name



    Question 4: Why Catchable fatal error?
    PHP Code:
    class {
            
        private 
    $name
        public static 
    $last_name 'default last name';    
        public function 
    name($name)
           {
              
    $this->name $name;
              return 
    $this
           }
        public function 
    lastName($last_name)
            {
                
    $this->last_name $last_name;
                return 
    $this;
            } 
        public function 
    show()
            {
                return 
    $this->name.", ".$this->last_name;     
            } 
        public static function 
    return_static()
            {
                return new 
    a();
            }       
    }

    $a = new a();

    $a a::return_static()->$a->name('Ben')->lastName('Salt')->show(); 
    Thank you
    Last edited by English Breakfast Tea; October 7th, 2013 at 11:49 PM.
  18. #10
  19. Wiser? Not exactly.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2001
    Location
    Bonita Springs, FL
    Posts
    5,958
    Rep Power
    4035
    Originally Posted by English Breakfast Tea
    Hi;
    Question 1:
    How is that I can access method show() while print_r($this); returns an empty object with no method in it? I mention later what manual says.
    print_r (and var_dump) do not show you methods, they only show you properties of an object. The methods are not a part of the objects data, they are part of the classes definition. An object of type X has all the methods defined by class X.

    Originally Posted by English Breakfast Tea
    Question 3: And it overwrites the value of the property for the life of the script for ONLY THAT OBJECT!

    I thought if the property is static, the value changes everywhere in the script So I expected the script below to print but it prints
    $this->last_name does not refer to the static $last_name property. To access static properties you need to use either self:: or static:: or class:: as the prefix, not $this->. What you did was create a local property $last_name on-the-fly rather than use the declared static $last_name. If you'd have had your error_reporting configured to E_ALL, you would have been alerted to this:
    Code:
    <?php
    
    class a {
    	public static $last_name='default';
    
    	public function test(){
    	    echo $this->last_name;
    	}
    }
    
    
    $o = new a;
    
    $o->test();
    PHP Notice: Undefined property: a::$last_name in - on line 7
    Originally Posted by English Breakfast Tea
    Question 4: Why Catchable fatal error?
    Your ->$a-> bit is wrong. There is no need for that portion of the code. You should have written:
    Code:
    $a = a::return_static()->name('Ben')->lastName('Salt')->show();
    which would result in $a containing the string returned by show().
    Recycle your old CD's, don't just trash them



    If I helped you out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud
  20. #11
  21. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,661
    Rep Power
    4124
    not a lot I can add, but I'm not sure how you expect to access a method of an "empty object". To me, empty means it has no properties or methods (eg new instance of stdClass).

    If you're trying to retrospectively work out what methods are available then try using reflection.

    When you return $this, your chaining code is still 'external' so you only have access to the public stuff (not the protected or private stuff) so its not like an inversion of privacy. Here's a simple test:
    PHP Code:
    //
    class foo() {
        public function 
    bar() {
        
            return 
    $this;
        }
        
        public function 
    baz() {
        
            return 
    $this;
        }
        
        private function 
    qux() {
        
            return 
    $this//irrelevant in this example
        
    }
    }

    $a = new foo;

    //this chaining

    $a->bar()->baz();

    //is equivalent to this

    $a->bar();
    $a->baz();


    //and this chaining

    $a->bar()->baz()->qux();

    //is equivalent to this

    $a->bar();
    $a->baz();
    $a->qux(); 

    As for method chaining, etc - the line of code in my sig is a real part f my current code base
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  22. #12
  23. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171
    1 -
    PHP Code:
    $a a::return_static()->$a->name('Ben')->lastName('Salt')->show(); 
    $a-> was typo, sorry.


    2 - It looks like return $this and return new "current class" are exact same thing!
    PHP Code:
    class Django{
            
       public function 
    function_one()
            {
                return 
    $this;
            } 
       public function 
    function_two()
           {
               return new 
    Django();
           } 

    $a = new Django();
    print_r($a->function_one());
    print_r($a->function_two()); 


    3 -
    What you did was create a local property $last_name on-the-fly rather than use the declared static $last_name. If you'd have had your error_reporting configured to E_ALL, you would have been alerted to this:
    This does:
    PHP Code:
    echo $a->lastName('Crui'); 
    BUt this does NOT! Wonder why! Did you know that?
    PHP Code:
    print_r($a->lastName('Crui')); 
    And this does not either:
    PHP Code:
    $a a::return_static()->name('Ben')->lastName('Salt')->show(); 
  24. #13
  25. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by English Breakfast Tea
    2 - It looks like return $this and return new "current class" are exact same thing!
    No, not at all. $this refers to the current instance. It doesn't create anything.

    On the other hand, new Django() creates a completely new object. It has the same class as $this, but it's a totally different object.



    Originally Posted by English Breakfast Tea
    3 - This does:
    PHP Code:
    echo $a->lastName('Crui'); 
    BUt this does NOT!
    All of those generate plenty of errors. This means your error reporting still isn't on. You need to turn it all up. Set it to -1.

    All three statements throw a Strict standards error (for the reason explained by kicken). And the first also throws a fatal error, because you cannot echo an object when there's no rule for converting it to a string -- that's what the __toString() method is for.

    Comments on this post

    • Northie agrees : got there first
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  26. #14
  27. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,661
    Rep Power
    4124
    - It looks like return $this and return new "current class" are exact same thing!
    No, DEFINITELY NOT!

    $this is the current instance, "new" is a new instance. Take the English means of the words "this" and "new"

    PHP Code:
    <?php

    class Django
             
       public function 
    function_one() 
            { 
                return 
    $this
            }  
       public function 
    function_two() 
           { 
               return new 
    Django(); 
           }
           
        public function 
    setFoo($foo) {
            
    $this->foo $foo;
        }
        
        public function 
    getFoo() {
            return 
    $this->foo;
        }
    }  
    $a = new Django(); 

    $b $a->function_two();

    $a->setFoo('alpha');
    $b->setFoo('bravo');

    print_r($a);
    print_r($b);

    $a->function_two()->setFoo('charlie'); //*

    print_r($a);
    print_r($b);
    Code:
    Django Object
    (
        [foo] => alpha
    )
    Django Object
    (
        [foo] => bravo
    )
    Django Object
    (
        [foo] => alpha
    )
    Django Object
    (
        [foo] => bravo
    )
    so where did charlie go?

    Answer is that charlie is a property of an object that has been created, but not assigned to a variable. It was created on the line marked by a *
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
  28. #15
  29. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,687
    Rep Power
    171
    Right,
    PHP Code:
    class book{
         public 
    $name "Original Name";
         public function 
    return_new()
            {
                return new 
    book();
            } 
        public function 
    return_this()
            {
                
    $this->name "New Name";    
                return 
    $this;
            }
        public function 
    what()
            {
                echo 
    $this->name;
            }    
    }

    $a = new book();
    print_r($a->return_new()->what()); //Prints Original Name
    print_r($a->return_this()->what());//Prints New Name 
    What could really help is to see what is happening during execution of the script and see all the objects at every step of the code. I see i can see all defined variables with this
    PHP Code:
    $arr get_defined_vars();
    print_r($arr); 
    Is there anyways that I can only see all created objects? I am pretty sure each object should have a specific id, time of creation etc. Can I somehow access that info? I started using Zend Studio's debugger and it is pretty good but t doesn't exactly do what I want, at least I don't know how to get it to. I attached a shot of what I see.



    Originally Posted by Jacques1
    All of those generate plenty of errors. This means your error reporting still isn't on. You need to turn it all up. Set it to -1
    I had this on my script but wasn't showing errors
    PHP Code:
    error_reporting(E_ALL);
    ini_set('display_errors', -1); 
    What I had to do:

    1 - Read Mystery of errors

    2 - Learn how to use vim to edit php.ini from Terminal

    3 - Change php.ini
    Code:
    error_reporting  =  -1
    display_errors = On
    dislay_startup_errors = On
    log_errors = Off
    4 - Restart Apache.

    Now I see all errors.






    Are these the same?
    PHP Code:
    self::$name;
    static::
    $name
    book
    ::$name 




    One other thing I like to learn is to deal with errors when chaining methods. Previously we had discussed exceptions but now seems to be the proper way to understand them.

    Should probably stop the rest of chaining as there is not any right values returned from a method.

    For example:
    PHP Code:
    class book{
         public 
    $name "Original Name";
         public function 
    return_new()
            {
                
    //If this method fails. For example cant connect to DB;
            

        public function 
    return_this()
            {
                
    $this->name "New Name";    
                return 
    $this;
            }
        public function 
    what()
            {
                
    //Or what if it fails here?
            
    }    
    }

    $a = new book();
    print_r($a->return_new()->what()); 
    print_r($a->return_this()->what()); 



    Thanks guys
    Attached Images
Page 1 of 2 12 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo