I have a PHP class, and I would like for it to have it so the variable is only a boolean?
class TestClass {
private $isTrue;
public function __construct ( $isTrue) {
$this -> isTrue = $isTrue;
}
public function getIsTrue ($isTrue) {
return $this -> isTrue;
}
public function setIsTrue ($isTrue) {
$this -> isTrue = $isTrue;
}
}
Or is it something that I am required to do in the setter and constructor like this?
class TestClass {
private $isTrue;
public function __construct ( $isTrue) {
$this -> isTrue = (bool)$isTrue;
}
public function getIsTrue ($isTrue) {
return $this -> isTrue;
}
public function setIsTrue ($isTrue) {
$this -> isTrue = (bool)$isTrue;
}
}
Yes, in PHP < 7, you have to do this manually, as you have done.
However, in PHP 7, you can use scalar typehinting to accomplish the same purpose:
<?php
class TestClass {
private $isTrue;
public function __construct(bool $isTrue) {
$this->isTrue = $isTrue;
}
public function getIsTrue() {
return $this->isTrue;
}
public function setIsTrue(bool $isTrue) {
$this->isTrue = $isTrue;
}
}
$tc = new TestClass(true);
var_dump($tc->getIsTrue()); //true
$tc->setIsTrue(false);
var_dump($tc->getIsTrue()); //false
$tc->setIsTrue(1);
var_dump($tc->getIsTrue()); //true
You can also enable strict-types mode, and the last case will throw an error:
<?php
declare(strict_types=1);
// ...same code here ...
$tc->setIsTrue(1);
var_dump($tc->getIsTrue());
Will produce:
Fatal error: Uncaught TypeError: Argument 1 passed to TestClass::setIsTrue() must be of the type boolean, integer given, called in /.../sth.php on line 27 and defined in /.../sth.php:16
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.