Method to set a number with int


#1

Hello,

I am doing coding exercises through the book that teaches about PHP OOP.

I am given the task to create a concrete method in the abstract class to set the number of articles. The way I have done differs from the solution but it works.

My question is, is there something important (a concept or notion) I’ve missed by not doing as it was depicted in the solution?

Thanks!

The way I have done it:
public function setNumberOfArticles($int)
{
$this->numberOfArticles = $int;
}

The way it is done in the solution:
public function setNumberOfArticles($int)
{
// Cast to integer type
$numberOfArticles = (int)$int;
$this->numberOfArticles = $numberOfArticles;
}

P.S.
I am using PHPStorm


#2

Well, you are just setting the variable while they are casting it to integer. Neither are checking for invalid data.

On PHP > 7 I’d do this instead

public function setNumberOfArticles(int $int) {
  $this->numberOfArticles = $int;
}

By type hinting values you will get a notice if you pass invalid data as you’d expect

Notice: A non well formed numeric value encountered on line 6


#3

Oh thanks, I’ve checked type hinting and it explains what it’s all about.

Thanks again