Can We Restrict PHP Variables to accept only certain type of values

后端 未结 3 1263
深忆病人
深忆病人 2021-01-03 08:23

i am wondering is it possible to restrict php variable to accept only certain type of variable it is defined to accept.

e-g if we see in C#

public in         


        
3条回答
  •  难免孤独
    2021-01-03 08:59

    No. PHP is not a strictly typed language. You can however use type hints in functions and methods.

    If class or interface is specified as type hint then all its children or implementations are allowed too.

    Type hints can not be used with scalar types such as int or string. Resources and Traits are not allowed either.

    The Scalar types being:

    • string
    • bool
    • int
    • float

    Examples:

    function (array $theArr) {
      // body
    }
    
    class X {
      public function __construct(SomeOtherClass $arg) {
        // body
      }
    
      public function setFoo(Foo $foo) {
    
      }
    }
    

    See the manual for more specifics: http://php.net/manual/en/language.oop5.typehinting.php

提交回复
热议问题