note 124041 added to language.oop5.typehinting

From: Date: Mon, 15 Jul 2019 23:20:25 +0000
Subject: note 124041 added to language.oop5.typehinting
Groups: php.notes 
Request: Send a blank email to php-notes+get-211609@lists.php.net to get a copy of this message
Sometimes you want to work with classes (not their instances), but Typehinting is only permitted for an object (instance). Here is sample code that tests whether the parameter is a valid type (the class/subclass/instance of an expected class): <?php declare(strict_types=1); class MyClass {}; function myfunc( $class ) { // Validate classname. if ( $class instanceof MyClass ) { $class = get_class( $class ); } elseif ( !class_exists( $class ) or !is_a( $class, MyClass::class, true ) ) { throw new \TypeError( "$class is not of type " . MyClass::class ); } // Proceed with processing of MyClass subclass ... } $myclass = new MyClass; myfunc( $myclass ); // valid myfunc( MyClass::class ); // valid myfunc( \String::class ); // not of type MyClass. ---- Server IP: 92.48.119.85 Probable Submitter: 173.63.128.218 ---- Manual Page -- http://php.net/manual/en/language.oop5.typehinting.php Edit -- https://master.php.net/note/edit/124041 Del: integrated -- https://master.php.net/note/delete/124041/integrated Del: useless -- https://master.php.net/note/delete/124041/useless Del: bad code -- https://master.php.net/note/delete/124041/bad+code Del: spam -- https://master.php.net/note/delete/124041/spam Del: non-english -- https://master.php.net/note/delete/124041/non-english Del: in docs -- https://master.php.net/note/delete/124041/in+docs Del: other reasons-- https://master.php.net/note/delete/124041 Reject -- https://master.php.net/note/reject/124041 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211609) next »