Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a value to PHP object property

Tags:

php

I'm working through a course on PHP and I'm completely stuck on one of the tasks.

The bit i'm stuck on is:

"PalprimeChecker [a function created just for this task] objects have a property called number. This task has two parts. First, assign that property a value of 17...."

The code I've written is returning an error and won't let me progress...

include('class.palprimechecker.php');


$checker = new PalprimeChecker();
$checker->number = '17';

echo "The number " . "$checker";
echo "(is|is not)";
echo " a palprime.";

I'm not sure at all where I'm going wrong with this. Anyone know the correct way to assign this value?

Hope you can help as I'm tearing my hair out!

Thanks!

like image 759
user2191622 Avatar asked Jul 15 '13 21:07

user2191622


2 Answers

Modify this :

echo "The number " . "$checker";

By This :

echo "The number " . $checker->number;

You were trying to print the entire object (which isn't possible without creating a method for it, check orangePill's answer for this), what you wanted to do is simply print the number inside the object.

Also note that you don't need to use quotes when assigning numbers. It might cause issues later on. You should simply assign it like this :

$checker->number = 17;
like image 74
Dany Caissy Avatar answered Nov 13 '22 16:11

Dany Caissy


You can also add a __toString method on the PalprimeChecker class.

public function __toString(){
      return (string)$this->number;
}

This will allow echo "The number " . $checker; to produce a string.

like image 31
Orangepill Avatar answered Nov 13 '22 16:11

Orangepill