SitePoint Sponsor

User Tag List

Page 3 of 4 FirstFirst 1234 LastLast
Results 51 to 75 of 90

Thread: inheritance

  1. #51
    SitePoint Guru dagfinn's Avatar
    Join Date
    Jan 2004
    Location
    Oslo, Norway
    Posts
    894
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ryan Wray
    The main benefit of interfaces and type hinting in PHP is that they enforce compliance. If something is not compliant, it is known sooner rather than later. For example, if a engine is passed in to a Car (via its constructor), and it doesn't implement IEngine, then we know there is an error. If we didn't use interfaces, then the error would occur when we try to call a method we expected to be implement in the Engine, but isn't. This stops things going wrong before they do, and ensures everything is how it should be.
    Yes, but...

    There is an upside and a downside. The upside is what you describe. The downside is that type hinting introduces dependencies. Every time you use an explicit class or interface name, you create a dependency on that class or interface. And unless you have a watertight naming scheme, any name conflict between classes or interfaces will be made that much worse by having many more occurences of the name.
    Dagfinn Reiersøl
    PHP in Action / Blog / Twitter
    "Making the impossible possible, the possible easy,
    and the easy elegant"
    -- Moshe Feldenkrais

  2. #52
    SitePoint Addict
    Join Date
    May 2005
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dagfinn
    Yes, but...

    There is an upside and a downside. The upside is what you describe. The downside is that type hinting introduces dependencies. Every time you use an explicit class or interface name, you create a dependency on that class or interface. And unless you have a watertight naming scheme, any name conflict between classes or interfaces will be made that much worse by having many more occurences of the name.
    I disagree. Type hinting is absolutely necessary in a dynamically typed language. If it didn't exist, you'd just be doing stuff like this instead:
    PHP Code:
    public function DoThing($Stuff)
    {
        if(!
    $Stuff instanceof SomeClass)
        {
            throw new 
    UselessRepeatedCodeException('What are you doing?');
        }

    The majority of code out there that would make use of type hinting is going to have those dependencies regardless of how you do it.

    Of course, there are still a few other issues with type hinting.

    1.) You can't catch errors (E_ERROR is triggered). Not *that* big of a deal since code relying on type hinting usually jumps into full-blown failure if it's not that type anyway.

    2.) You can't type hint primitives. You're still forced to type cast ints, floats, and strings. Silly.

  3. #53
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What are you saying?
    I'm saying that the feeling I get is that PHP5 was rushed Not in the sense of the arguements we've all had in earlier threads, as such there is nothing wrong with PHP5 in it's self as a language.

    But there are issues with the implementation of the object model, or the lack of such as the example I gave above? The implementation of that into the object model should have been taken into consideration before the release of PHP5 was made.

    I question why was it left out in the first place? If we had, had that functionality then it just makes our lifes that bit easier. Don't you think...

    And yes, we could have done with type hinting primitives as well, which begs the question why was it left out as well? Subtle things like that make a difference, when you use them day to day, you notice just how much helpful it is to you

  4. #54
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Ireland
    Posts
    349
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dagfinn
    And unless you have a watertight naming scheme, any name conflict between classes or interfaces will be made that much worse by having many more occurences of the name.
    Hopefully namespace support or similar will come along so all interfaces/classes don't have to be unique. For the time been, you can always avoid it in an ugly fashion:
    NOT IEngine
    BUT PackageName_IEngine

    Not pretty, but it should avoid most namespace conflicts. Most developers probably don't do this for their own projects, but we see naming styles like this in some classes (e.g. PEAR).

  5. #55
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Etnu
    The majority of code out there that would make use of type hinting is going to have those dependencies regardless of how you do it.
    The question is, what are you basing your dependencies on? What the class is called, or what the object does?

    In the second case, you don't have the dependency on the class name, you don't need the extra if instanceof code, and you don't need type hinting.

    Remember the change in Javascript development a couple of years back, when people moved from testing if browser name == IE5 to if browser supports getElementById? It is much the same as testing against types vs methods, and you get the same benifits. If a new browser comes along (say Firefox) that supports getElementById, the Javascript just keeps on working. The same as if you passed a mock object instead of a real one to test a class, you'd reduce the complexity of the class you are testing, and you wouldn't have to jump through hoops on the testing side to match up type names.

    EDIT: reducing complexity is a big thing, and if dynamic types and duck typing gets me that, all the best to them.

    Later,
    Douglas
    Hello World

  6. #56
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Etnu
    I disagree. Type hinting is absolutely necessary in a dynamically typed language. If it didn't exist, you'd just be doing stuff like this instead:
    PHP Code:
    public function DoThing($Stuff)
    {
        if(!
    $Stuff instanceof SomeClass)
        {
            throw new 
    UselessRepeatedCodeException('What are you doing?');
        }

    Of course you wouldn't for crying out loud!

    If you have instanceof, than you have (partially) strong typing, so the whole point is missed. What you should ideally be able do is:

    PHP Code:

    public function DoThing($Stuff)
    {
        try {
            
    $stuff->doSomething();
        }
        catch(
    $e) {
            
    $e->handleExceptionOneWayOrAnother();
        }

    That's it! If your $Stuff object has the doSomething() method, everything's fine; otherwise, catch the exception.

  7. #57
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    function do_thing $stuff )
    {
        
    $stuff->doSomething();
    }
    catch ( 
    $e )
    {
        
    $this->handle_exception_one_way_or_another($e);

    Hmm, yummy.

    But yes, what you're saying is basically what most people would like: why can't exceptions and errors just get allong better with eachother? It would be good if we could catch errors with a try {} block...

    Douglas
    Hello World

  8. #58
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DougBTX
    It would be good if we could catch errors with a try {} block...
    Perhaps with a custom error handler? It might be an interesting little project if I had the time...

    You know, like:

    PHP Code:
    // PSEUDOCODE!
    function errors2exceptions($errno$erstr$errfileerrline)
    {
        if(
    $errno == E_ERROR) {
            throw new 
    ErrorException();
        }
        
    // yadda yadda yadda
    }

    set_error_handler("errors2exceptions"); 

  9. #59
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    All of which ignores the fact that the PHP engine says both missing methods and type hinting failures are fatal errors so a custom error handler will never touch them
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.

  10. #60
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by sweatje
    All of which ignores the fact that the PHP engine says both missing methods and type hinting failures are fatal errors so a custom error handler will never touch them
    We could make ourselves a new Object and call it a root object, and have this:

    PHP Code:
    class Object
    {
        function 
    __call (...)
        {
            throw new 
    ErrorException();
        }

    And we could throw it into our PHP code rewriter that we didn't want to write before, to do automagically replace this:

    PHP Code:
    class Klass
    {
      
    /* ... */

    With this:

    PHP Code:
    class Klass extends Object
    {
        
    /* ... */

    Hay, if we came up with come dynamic constructs which can compile down to normal-PHP (such as anonymous functions) it might provide evedence that these sorts of things are useful in PHP...

    Douglas
    Hello World

  11. #61
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by BerislavLopac
    Perhaps with a custom error handler? It might be an interesting little project if I had the time...

    You know, like:

    PHP Code:
    // PSEUDOCODE!
    function errors2exceptions($errno$erstr$errfileerrline)
    {
        if(
    $errno == E_ERROR) {
            throw new 
    ErrorException();
        }
        
    // yadda yadda yadda
    }

    set_error_handler("errors2exceptions"); 
    http://www.sitepoint.com/forums/show...89&postcount=4

  12. #62
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    All of which ignores the fact that the PHP engine says both missing methods and type hinting failures are fatal errors so a custom error handler will never touch them
    Things just couldn't get any better...

    Stereofrog,

    Had a look at your link you've posted, and what is the use of that example, when you have access to the error data from the Exception anyways? Maybe someone could explain the benifits of it which I've obviously missed out on.

  13. #63
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by sweatje
    All of which ignores the fact that the PHP engine says both missing methods and type hinting failures are fatal errors so a custom error handler will never touch them
    Indeed, fatals are the matter of problem. If this weren't fatals, we could discuss something more interesting...

    Quote Originally Posted by DougBTX
    We could make ourselves a new Object and call it a root object, and have this:
    IIRC the only real way to catch fatals is something like
    PHP Code:
    ob_start('catchFatals');

    function 
    catchFatals($buf) {
        if(!
    preg_match("~Fatal error: (.+?) in (.+?) on line (\d+)~"$buf$m))
            return 
    $buf;
        list(, 
    $err$file$line) = $m;
        return 
    "Zend sucks in $file on line $line. The error was $err.";
    }

    new 
    NoSuchClass(); 
    Not that helpful, since the app is in any case down, but at least you get a chance to log an error and provide a nicer output to end user.

  14. #64
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    Had a look at your link you've posted, and what is the use of that example, when you have access to the error data from the Exception anyways? Maybe someone could explain the benifits of it which I've obviously missed out on.
    The use of that example is to convert Errors to Exceptions. The only thing you can do about Error is to log it and terminate an application. With Error you know WHAT happened, but you have no idea WHY, since the context is lost. Exception is an object like any other in your application and can be handled within normal application flow.

  15. #65
    PEACE WILL WIN abalfazl's Avatar
    Join Date
    Feb 2005
    Location
    Beyond the seas there is a town
    Posts
    711
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Polymorphism without inheritance

    Hello firends


    From this site:


    http://www.artima.com/designtechniques/interfaces3.html





    Getting more polymorphism


    Interfaces give you more polymorphism than singly inherited families of classes, because with interfaces you don't have to make everything fit into one family of classes. For example:


    interface Talkative {
    void talk();
    }
    abstract class Animal implements Talkative {
    abstract public void talk();
    }
    class Dog extends Animal {
    public void talk() {
    System.out.println("Woof!");
    }
    }
    class Cat extends Animal {
    public void talk() {
    System.out.println("Meow.");
    }
    }
    class Interrogator {
    static void makeItTalk(Talkative subject) {
    subject.talk();
    }
    }

    Given this set of classes and interfaces, later you can add a new class to a completely different family of classes and still pass instances of the new class to makeItTalk(). For example, imagine you add a new CuckooClock class to an already existing Clock family:


    class Clock {
    }
    class CuckooClock implements Talkative {
    public void talk() {
    System.out.println("Cuckoo, cuckoo!");
    }
    }

    Because CuckooClock implements the Talkative interface, you can pass a CuckooClock object to the makeItTalk() method:


    class Example4 {
    public static void main(String[] args) {
    CuckooClock cc = new CuckooClock();
    Interrogator.makeItTalk(cc);
    }
    }

    With single inheritance only, you'd either have to somehow fit CuckooClock into the Animal family, or not use polymorphism. With interfaces, any class in any family can implement Talkative and be passed to makeItTalk(). This is why I say interfaces give you more polymorphism than you can get with singly inherited families of classes


    That example isn't about PHP,That's about JAVA.But I know OOP in PHP and JAVA is pretty similar.I guess that the same thing like that is possible in PHP.

    May someone explain about this subject(getting more polymorphism while using interface ,without inheritance) please?

    (by give an example in PHP)



    Thanks in advance and
    GOOD LUCK!

  16. #66
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by abalfazl
    That example isn't about PHP,That's about JAVA.But I know OOP in PHP and JAVA is pretty similar.I guess that the same thing like that is possible in PHP.
    Take this bit:

    "With single inheritance only, you'd either have to somehow fit CuckooClock into the Animal family, or not use polymorphism."

    Ask yourself, "why only those two options?"

    The answer is static typing, without static typing we have more options.

    Here's an example of polymorphism without explicit interfaces or inheritance:

    PHP Code:
    class Man
    {
        function 
    talk ( )
        {
            echo 
    "Hi there sugar!";
        }
    }

    class 
    Woman
    {
        function 
    talk ( )
        {
            echo 
    "Hello darling.";
        }
    }

    if ( 
    rand(110) > )
    {
        
    $person = new Man;
    }
    else
    {
        
    $person = new Woman;
    }

    $person->talk(); 
    This technique is called Duck typing.

    hth,
    Douglas
    Hello World

  17. #67
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs hasattr() tests or EAFP programming.
    From, http://en.wikipedia.org/wiki/Duck_typing which might help you

    And here is an interesting read btw, http://www.manageability.org/blog/st...ck-typing/view

  18. #68
    SitePoint Guru dbevfat's Avatar
    Join Date
    Dec 2004
    Location
    ljubljana, slovenia
    Posts
    684
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DougBTX
    ...
    Here's an example of polymorphism without explicit interfaces or inheritance:
    ...
    Hmm, it makes me think ...

    Since the code that uses the object calls talk() on whatever object it gets, I suppose demanding a certain interface (that introduces the method) is ok.

    I think it boils down to checking the interface of an object before it enters the scope and when the method is called. But the latter method could be dangerous -- what if some critical code was already succesfully executed within the scope and then it fails because the object's method cannot be called? Or what if this object has the method, but it doesn't nearly do what it's expected to?

    Regards

  19. #69
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dbevfat
    I think it boils down to checking the interface of an object before it enters the scope and when the method is called.
    Spot on.

    Quote Originally Posted by dbevfat
    what if some critical code was already succesfully executed within the scope and then it fails because the object's method cannot be called? ... Or what if this object has the method, but it doesn't nearly do what it's expected to?
    Method naming and variable naming become more important if they are the only things you write down, though if they are the only things you have to write down you'll pay more attention to them anyway.

    Keeping things explicit (safer) is a trade-off against keeping things dynamic (more free), there's a good high-level perspective on that here, "Freedom languages" vs "Safety languages".

    Depending on your past experience, type hinting probably sounds like a drop of sanity, or a blot on the landscape; I'm in the latter camp, come join me

    Regards,
    Douglas
    Hello World

  20. #70
    SitePoint Guru 33degrees's Avatar
    Join Date
    May 2005
    Posts
    707
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DougBTX
    Depending on your past experience, type hinting probably sounds like a drop of sanity, or a blot on the landscape; I'm in the latter camp, come join me

    Regards,
    Douglas
    Type hinting is optional though, isn't it?

  21. #71
    SitePoint Wizard DougBTX's Avatar
    Join Date
    Nov 2001
    Location
    Bath, UK
    Posts
    2,498
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by 33degrees
    Type hinting is optional though, isn't it?
    In PHP, of course. It would break all existing code if it wasn't

    Douglas
    Hello World

  22. #72
    SitePoint Addict
    Join Date
    May 2005
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DougBTX
    The question is, what are you basing your dependencies on? What the class is called, or what the object does?

    In the second case, you don't have the dependency on the class name, you don't need the extra if instanceof code, and you don't need type hinting.

    Remember the change in Javascript development a couple of years back, when people moved from testing if browser name == IE5 to if browser supports getElementById? It is much the same as testing against types vs methods, and you get the same benifits. If a new browser comes along (say Firefox) that supports getElementById, the Javascript just keeps on working. The same as if you passed a mock object instead of a real one to test a class, you'd reduce the complexity of the class you are testing, and you wouldn't have to jump through hoops on the testing side to match up type names.

    EDIT: reducing complexity is a big thing, and if dynamic types and duck typing gets me that, all the best to them.

    Later,
    Douglas
    That approach works for framework type code, and little else. If you *really* think writing 800 tests for various support of methods (wait, you have no way to check the signature! sorry, that's out!) instead of just checking to see if a particular object is a certain class, be my guest. I personally like to get projects done in a reasonable amount of time.

    Of course, you can check for Interface implementations, but that leaves you with the exact same problem that you're trying to avoid (now you're depending on an INTERFACE with a specific name, not specific functionality). Interfaces are useful in the rare case that you need to be able to pass a generic object to a method and have something consistently done with it (although multiple inheritence would be preferrable, so that you don't have to write the same code 10 times). An example would be the way that PHP implements __toString(), __call(), __set(), __get(), __construct, __destruct, and (if enough people on internals agree with me __dump()).

    Even the signature checking method (if it existed in PHP) wouldn't work, because there are plenty of functions out there that accept multiple parameters of the same type (in the same order), and return the same data type. Most of php's string functions come to mind immediately (strpos and strrpos would appear identical to such a system).

    Very little code will ever need to deal with generic objects. If all the code you ever write is frameworks and unit testing tools, then you'll probably disagree -- but when you're writing ordinary, everyday production code, it just doesn't happen that often, and when it does, you're usually dealing with objects that all derive from the same parent (or you use an interface to test against).

    My personal preference would simply be to support BOTH MI & interfaces (they each serve unique purposes, and are not / should not be mutually exclusive). In C++ you can already do this by using pure virtual classes. Type hinting should act on whether the passed in object implements or derives from either.

    Ultimately, type hinting is the easiest way to ensure that the passed in object is going to be suitable for whatever comes next *in PHP*. It's certainly not everything to everyone, but it works well.

  23. #73
    SitePoint Addict
    Join Date
    May 2005
    Posts
    255
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by sweatje
    All of which ignores the fact that the PHP engine says both missing methods and type hinting failures are fatal errors so a custom error handler will never touch them
    This should be resolved soon. Check PHP internals mailing list.

  24. #74
    SitePoint Guru dagfinn's Avatar
    Join Date
    Jan 2004
    Location
    Oslo, Norway
    Posts
    894
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This discussions mirrors one that's been happening on and off in comp.object for a long time (althouhg I haven't followed it for a while). The question of whether type hints are worth the trouble is closely related to the question of whether static typing is worth the trouble. (You could say type hints does the same thing as static typing, only less of it.)

    Some gurus including Uncle Bob (Robert C. Martin) say that unit testing changes the equation, since you can catch the errors that would be caught by the compiler in a statically typed language.
    Dagfinn Reiersøl
    PHP in Action / Blog / Twitter
    "Making the impossible possible, the possible easy,
    and the easy elegant"
    -- Moshe Feldenkrais

  25. #75
    SitePoint Guru dbevfat's Avatar
    Join Date
    Dec 2004
    Location
    ljubljana, slovenia
    Posts
    684
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by DougBTX
    Keeping things explicit (safer) is a trade-off against keeping things dynamic (more free), there's a good high-level perspective on that here, "Freedom languages" vs "Safety languages".
    Thanks for the resource, it looks promising and I'll read it when I get to it.

    Quote Originally Posted by DougBTX
    Depending on your past experience, type hinting probably sounds like a drop of sanity, or a blot on the landscape; I'm in the latter camp, come join me
    Might happen . I have root in Pascal, so type-hinting is natural to me. With php4 I didn't actually miss it, but there were times when I really wanted to be 100% sure about an object ...


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
  •