|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-08-03 18:10 UTC] corey at eyewantmedia dot com
Description:
------------
The problem is that you can't type hint a primitive type in a function declaration and use the function with a primitive type. No primitive types work, so every function (to be safe) has to do some sort of
if(is_int($x)) {
// do stuff
} else {
die("Must be an int!");
}
Since php scalars are so loosely typed, it seems like it would be good practice to require a specific type of argument when the logic contained in the function demands a specific type of variable. It saves TONS of code.
I am running the default compile of 5.0 for windows, with mysqli, curl, and mcrypt enabled. I have all errors printing since this is in devlopment, but this bug is a fatal error so I think it would print out anyway.
Reproduce code:
---------------
<?php
Class Test {
private $i;
private $d;
private $s;
private $b;
public function SetI(int $x) { $this->i = $x; }
public function SetD(double $x) { $this->d = $x; }
public function SetS(int $x) { $this->s = $x; }
public function SetB(int $x) { $this->b = $x; }
}
$o = new Test();
$o->SetI(4);
$o->SetD(4.65);
$o->SetS("yay");
$o->SetB(false);
?>
Expected result:
----------------
I expect $o->SetI(4) to accept 4 since 4 is an int (and is_int(4) returns true), $o->SetD(4.65) to accept 4.65 since it is a double, $o->SetS("yay") to accept "yay" since it is a string, and $o->SetB(false) to accept false, since it is a bool.
Actual result:
--------------
Fatal error: Argument 1 must be an object of class [int, string, double, bool] in test.php on line X
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 12:00:02 2025 UTC |
Also, if type hinting with primitive types is not to be implemented, then the zend php5 documentation is wrong. If you look under the exceptions section, they have this snippet of code on how to extend the exception class: <?php class Exception { function __construct(string $message=NULL, int code=0) { if (func_num_args()) { $this->message = $message; } $this->code = $code; $this->file = __FILE__; // of throw clause $this->line = __LINE__; // of throw clause $this->trace = debug_backtrace(); $this->string = StringFormat($this); } //... more stuff here } ?> You can find this code here: http://www.zend.com/php5/articles/engine2-php5-changes.php#Heading12 That code does not run; it produces the same error as my sample class code.