jwknz
jwknz

Reputation: 6822

PHP - destruct clarification

I am just learning OOP with PHP and I am trying to get my head around this:

I am using php version 5.6.10 on my MAMP installation if that makes a difference??

This the code I have:

<?php

    class Baddie {
        public $evilness = 10;
    }

    class Boss extends Baddie {
        public $evilness = 50;

        public function changeEvilness($value)
        {
            //$this->$evilness = $value; Had this, which was a typo
            $this->evilness = $value;
        } 

        public function __destruct() {

            echo "You beat the boss!";
        }

    }

    $ganon = new Boss;

?>

//Note the code is from Rob Percivals Udemy course, hence the gaming references.

So when I call a new instance of the Boss class, it gets destroyed automatically. This prevents me from changing the "evilness" of the boss.

How do I change the code, or maybe a php setting that the destruct() is not called automatically, but only with the unset() function so that I can call other methods from with that class?

Changes I have updated the typo error, but the answers provided still apply.

Upvotes: 0

Views: 106

Answers (1)

Wessel van der Linden
Wessel van der Linden

Reputation: 2622

I tested the code below and it works? You have to change $this->$evilness to $this->evilness in the changeEvilness function

<?php

    class Baddie {
        public $evilness = 10;
    }

    class Boss extends Baddie {
        public $evilness = 50;

        public function changeEvilness($value)
        {
            $this->evilness = $value;
        } 

        public function __destruct() {

            echo "You beat the boss!";
        }

    }

    $ganon = new Boss;
    echo $ganon->evilness ."\n";
    $ganon->changeEvilness(1337);
    echo $ganon->evilness ."\n";
?>

this outputs:

50
1337
You beat the boss!

So as you can see, the constructor, changeEvilness() function and the destructor all get called.

Also it's good to know that the php process ends when the last line of code is reached. So because you have nothing after the $ganon = new Boss, it will stop the php process and call the destructor.

Upvotes: 1

Related Questions