Question

So if I build a class...

class Foo {
    public $_string;
    public function($sString = 'new string') {
        $this->_string = $sString;
    }
}

I would like to forcibly say that $sString is of type string in my function arguments, something like this...

class Foo {
    public $_string;
    public function(string $sString = 'new string') {
        $this->_string = $sString;
    }
}

but my IDE says "Undefined class 'String'" and php will throw errors, so is there a way to forcibly say what type of variable is being passed into a function in a class or would I have to declare it inside the function like this...

class Foo {
    public $_string;
    public function($sString = 'new string') {
        $this->_string = (string)$sString;
    }
}

any help would be appreciated. Thank you.

Was it helpful?

Solution 2

What you're describing is "type hinting" and PHP supports it, however (for some reason) it does not allow it for any of the built-in intrinsic types or string ( http://php.net/manual/en/language.oop5.typehinting.php ) which explains the problem you're having.

You can workaround this by manually calling is_string inside your function, but things like this aren't necessary if you control your upstream callers.

OTHER TIPS

Not today. PHP 5.4 may have a scalar type-hint, but this has been proposed subsequently dropped before.

All you can do is an is_string() check in the body.

you can use is_string function to check it.

if (is_bool($message)) {
  $result = 'It is a boolean';
}
if (is_int($message)) {
  $result = 'It is a integer';
}
if (is_float($message)) {
  $result = 'It is a float';
}
if (is_string($message)) {
  $result = 'It is a string';
}
if (is_array($message)) {
  $result = 'It is an array';
}
if (is_object($message)) {
  $result = 'It is an object';
}

check this.

class Foo {
    public $_string;
    public function($sString = 'new string') {
        if (is_string($sString)) {
           $this->_string = $sString;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top