PHP function param type best practices

前端 未结 3 572
梦毁少年i
梦毁少年i 2021-01-03 09:42

I am currently working on a framework and have come accros a snag... how should I handle incorrect parameter types when someone calls a function in the framework?

Ex

相关标签:
3条回答
  • 2021-01-03 09:45

    I would typecast the int and string datatypes automatically with no complaint (because they could be easy to mix up), but for something like a resource or object it could be a useful feature to notify the programmer of an error.

    I would also set up the notification code in its own function so things wouldn't get so repetitive. Anyways, Good luck!

    0 讨论(0)
  • 2021-01-03 09:49

    If anything, just use SPLTypes and be done; otherwise throw InvalidArgument exceptions

    0 讨论(0)
  • 2021-01-03 09:50

    It depends.

    PHP is a dynamically typed language, and sometimes for a good reason. Since it deals a lot with HTTP data, which is all strings all the time, numbers aren't necessarily always of type int and will still work fine for general operations.

    Strictly enforcing primitive types is often very un-PHPish and could be a hassle to work with.

    The usual way to do things in PHP is to accept arguments in almost any type and work with them in good faith until you need to have specific results or the type becomes an issue.

    function example1($title, $comment_num) {
    
        // do some operations that should work error-free regardless of type
    
        if ($result != 'something specific you expect here') {
            throw new Exception('Something went wrong!');
            // or
            trigger_error('Something went wrong!');
            return false;
        }
    
        // continue with $result
    }
    

    You can go the OOP route and construct objects this way. Objects will be flexible to some degree in what they accept. If they succeed in being constructed, you have a defined object of a specific type that you can use for PHP-enforced type hinting:

    function example1(TitleObject $title) {
        // rest assured that $title is of the right type
    }
    
    0 讨论(0)
提交回复
热议问题