我正在学习 PHP 7 中的 OOP,遵循一本书上的示例。关于代码
<?php
class Book {
public $isbn;
public $title;
public $author;
public $available;
public function getPrintableTitle() : string {
$result = '<i>'. $this -> title
. '</i> - '. $this -> author;
if (!$this->available) {
$result .= ' <b>Not available</b>';
}
return $result;
}
public function getCopy(): bool{
if ($this -> available < 1) {
return false;
} else {
$this -> available--;
return true;
}
}
public function __construct(
int $isbn,
string $title,
string $author,
int $available
) {
$this -> isbn = $isbn;
$this -> title = $title;
$this -> author = $author;
$this -> available = $available;
}
}
$book = new Book(98765432123457, '1984', 'George Orwell', 12);
if($book->getCopy()) {
echo 'Here, your copy. <br />';
} else {
echo 'Sorry, no copies available for this book. <br />';
}
var_dump($book->isbn);
?>
我收到一条错误消息:
致命错误:未捕获的类型错误:传递给 Book::__construct() 的参数 1 必须是整数类型,给定浮点数,在 /home/jorge/Learning/php_sandbox/book.php 第 39 行调用,并在 /home/jorge/Learning/ 中定义php_sandbox/book.php:26 堆栈跟踪: #0 /home/jorge/Learning/php_sandbox/book.php(39): Book->__construct(98765432123457, '1984', 'George Orwell', 12) #1 {main } 放入 /Learning/php_sandbox/book.php 第 26 行
尝试搜索 php 在线文档,但找不到此错误的原因。在我看来 php 正在解释int98765432123457 作为float因为语句末尾有逗号。如果是这样,有办法解决吗?
您的 ISBN 98765432123457 仅比无符号 32 位整数的大小稍大一些。 (日志 98765432123457 == 32.22376878216809)。
我怀疑当 PHP 解析你的源代码时,它会将数字字符串内部化为浮点数,以便表示比可以编码为 32 位 int 的数字更大的数字。
虽然 ISBN 仅使用数字,但我不认为它们是数字。 (毕竟,前几位数字指定一个国家/地区,有些表示形式有破折号,有些表示形式有前导 0。)我会用字符串来表示。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)