0

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.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Rob
  • 237
  • 2
  • 9

3 Answers3

2

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • 5.4 will not get scalar type hinting. 5.5 also probably not, but who knows maybe somebody from internals can make a nice patch and and convince rasmus. One can hope can't he? – PeeHaa Mar 12 '13 at 09:33
1

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.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • I know about using is_string() and is_array, or is_xxx... to check for types of variables, I was just hoping I could forcibly say what type of var was going into the function. Not even for me, but for a large scale project where we have multiple devs working on the same code base, it would be nice to have that force check that will tell teh other devs if they are using it wrong. Thank you for the help though, hopefully php will step up and give us devs better control over our vars. – Rob Mar 12 '13 at 03:44
0

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;
        }
    }
}
Dino Babu
  • 5,814
  • 3
  • 24
  • 33