July 12, 201412 yr Hi, still learning and thought i'd find exercises online. I came across the following problem. Exercise 1: Charlie bit my finger! Part 1: Charlie will bite your finger exactly 50% of the time. First, write a function isBitten() that returns TRUE with 50% probability, and FALSE otherwise. Hint: You may find the rand() function useful. Part 2: Below the function, write code to generate a webpage that displays “Charlie bit your finger!” or “Charlie did not bite your finger!” using the isBitten() function. Firstly I came up with the following syntax, but it was producing an error as it didnt line 5 with the rand() function. The error was Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\xampp\htdocs\_\php\index.php on line 5 <?php class bite { public $bitten = rand(0, 100); public function isBitten() { if ($this->bitten > 50) { echo "BITTEN" . $this->bitten; } else { echo "NOT" . $this->bitten; } } } ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php $myBite = new bite(); $myBite->isBitten(); ?> </body> </html> But after using a __constructor it resolved the issue. Can someone tell me why this code worked and my first attempt didn't. Sorry still a newbie. <?php class bite { public $bitten; function __construct($rand) { $this->bitten = $rand; } public function trueorfalse() { if ($this->bitten > 50) { echo "true = $this->bitten"; } else { echo "false = $this->bitten"; } } } ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php $rand = rand(0, 100); $myBite = new bite($rand); $rtnValue = $myBite->trueorfalse(); ?> </body> </html>
July 13, 201412 yr Hello!In short, you need to use literals when assigning a default value to a class property outside the constructor. In English, you'd need to use simple fixed values---no calculations, functions, or anything of a similar nature. For example: private $laziness_level = 9001; // this will work private $laziness_level = "Too lazy to get up for the remote"; // this will work too private $laziness_level = 100*100*100*100*100; // this will NOT work because it involves computation private $laziness_level = getRemote()->getFatigue(); // this Will NOT work. Functions involved. Save fancy computations and function references for the constructor or methods in general. Regards! Edited July 13, 201412 yr by Pete Prosper
Create an account or sign in to comment