In PHP, we can set property values for objects through the set function. However, sometimes we may need to delete the set value. So, how to delete it?
In fact, it is not difficult to delete the value of set. We just need to call the unset function. Specifically, you can follow the following steps:
$obj = new stdClass();
$obj->name = 'Tom';
unset($obj->name);
In this way, we successfully deleted the set value.
In addition to the above example, we can also delete the set value in the class. For example, suppose we have a Book class, which contains a title attribute:
class Book { private $title; public function setTitle($title) { $this->title = $title; } } $book = new Book(); $book->setTitle('PHP');
At this point, we can use the following code to delete the title attribute:
unset($book->title);
Of course, we can also use the Book class Add a method to delete the title attribute as follows:
class Book { private $title; public function setTitle($title) { $this->title = $title; } public function unsetTitle() { unset($this->title); } } $book = new Book(); $book->setTitle('PHP'); $book->unsetTitle();
In short, through the unset function, we can easily delete the value of the set. You can use this method to delete properties whether in an object or in a class. At the same time, it should be noted that before deleting an attribute, you should first determine whether the attribute exists, otherwise an error may occur.
The above is the detailed content of Detailed explanation of how to delete the value of set in php. For more information, please follow other related articles on the PHP Chinese website!