Type hinting for any object

后端 未结 9 1633
梦毁少年i
梦毁少年i 2020-12-14 05:43

I\'ve been working on code that\'s intended to be used with objects, without really caring what the kind of object is. I wanted to type hint that the method being written ex

相关标签:
9条回答
  • 2020-12-14 06:09

    As of php 7.2 this feature has now been implemented. you can type hint for any object now.

    function myFunc(Object $myObject) : Object {
        return $myObject;
    }
    

    You can review this in the official documentation

    0 讨论(0)
  • 2020-12-14 06:13

    stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

    0 讨论(0)
  • 2020-12-14 06:13

    Although there is no type hinting for objects, you can use:

    if (!is_object($arg)) {
        return;
    }
    
    0 讨论(0)
  • 2020-12-14 06:19

    There is no base class that all objects extend from. You should just remove the typehint and document the expected type in the @param annotation.

    0 讨论(0)
  • 2020-12-14 06:20

    You could do something like this:

    function myFunc ($obj)
    {
         if ($obj instanceof stdClass) { .... }
    }
    
    0 讨论(0)
  • 2020-12-14 06:25

    Well it only took eight years, but this will soon be possible: PHP 7.2 introduces the object type hint! As I write this, it's currently in the RFC stage, and is due to be released in November.

    Update, 30th November: PHP 7.2 has been released

    RFC: Object typehint

    Discussion

    This behaves exactly as you might expect:

    <?php
    
    class Foo {}
    class Bar {}
    
    function takeObject(object $obj) {
        var_dump(get_class($obj));
    }
    
    takeObject(new Foo);
    takeObject(new Bar);
    takeObject('not an object');
    

    Will result in:

    string(3) "Foo"

    string(3) "Bar"

    Fatal error: Uncaught TypeError: Argument 1 passed to takeObject() must be an object, string given, called in...

    See https://3v4l.org/Svuij

    One side-effect of this is that object is now a reserved word, which unfortunately renders @Gaz_Edge's existing solution above broken. Fortunately, all you have to do to fix it is delete the interface.

    0 讨论(0)
提交回复
热议问题