In PHP ****The following code assumes that a class Counter exists, it creates a
ID: 3846606 • Letter: I
Question
In PHP ****The following code assumes that a class Counter exists, it creates a new object of the Class counter and then it increases the counter two times. At the end, it echo's the current value of the counter on the console, which should be equal to 2 if everything worked.
Instructions
Fill the content of the class Counter to make it behave as expected.
HINT:
The class needs to have an attribute called $currentValue set to 0 at the beginning.
The class needs to have a function called increaseOne that increases $this->currentValue in one every time is called. That function does not need to return anything.
To access class variables you have to use $this->variableName instead of $variableName.
The value echoed to the console should be equal to 2.
___________________________________________
$myNewCounter = new Counter();
$myNewCounter->increaseOne();
$myNewCounter->increaseOne();
echo $myNewCounter->currentValue;
/*****EDIT ONLY BELOW HERE*****/
//Help with code here.
Explanation / Answer
Hi,All we have to do is create a class named counter with field currentValue set to 0 at the beginning, we can do that like below
<?php
$myNewCounter = new Counter();
$myNewCounter->increaseOne();
$myNewCounter->increaseOne();
echo $myNewCounter->currentValue;
class Counter { // defining a class named counter
var $currentValue=0; // initializing to zero.
function increaseOne(){ // defining the counter function.
$this->currentValue++;
}
}
?>
So, here we defined a class and a member function to increase the countervalue by 1. $this is a special variable and it refers to the same object ie. itself.
The o/p of the above program can be seen here.- http://ideone.com/4OZqji
Let me know if you have any additional doubts,
Good day
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.