0

I'm reading "Up and Running Laravel" book and regularly come across examples like:

class Contact extends Model
{
  public function phoneNumer()
  {
     return $this->hasOne(PhoneNumber::class);
  }
}

The explanation in the book:

As you can tell, the methods defining realationships are on the Eloquent model itself ($this->hasOne()) and take, at least in this instance, the fully qualified class name of the class that you're relating them to.

Since I don't really understand it, I looked up php.net and found this:

The class keyword is also used for class name resolution. To obtain the fully qualified name of a class ClassName use ClassName::class. This is particularly useful with namespaced classes.

Is it just necessary so php knows that PhoneNumber is a class? In other words, if it was:

return $this->hasOne(PhoneNumber);

I guess I would get an error/warning because php has no idea that we are talking about the class? Otherwise, the return is within the class so I thought it should be clear that the class name is meant?

Could anyone explain to me like you would explain it to your 5 year old son?

Wondarar
  • 171
  • 3
  • 5
  • 19
  • 1
    Without `::class`, PHP wouldn't know you were talking about a class at all. – prieber May 19 '21 at 19:01
  • 2
    In general [fully qualified class name](https://www.php.net/manual/en/language.namespaces.rules.php) is a class with namespace, when is valid ends with `::class` it returns string with that path. – biesior May 19 '21 at 19:01
  • 1
    Also, if in sample only class name is used without namespace, that means that it **had to** be imported earlier in the script i.e. with `use \Full\Namespecae\PhoneNumber;`, or it is called in the same namespace, hard to guess, would be better if we knew the link to the docs you're reading now. – biesior May 19 '21 at 19:13
  • 1
    book: "Laravel: Up & Running: A Framework for Building Modern PHP Apps 2nd Edition", p 140; just checked it again. The author noted on p131: "You may have noticed that several of these examples have used the class Contact, with no namespace. This is abnormal, and I've only done this to save space in the book. Normally even your top-level models would live at something like App\Contact." – Wondarar May 19 '21 at 19:22
  • 1
    I thought so, I wouldn't write the book just to *save the place*, of course under some circumstances it *can* be shortened, but it **should** be described. – biesior May 19 '21 at 19:24
  • 1
    Tip: use some good IDE (PhpStorm is good, this not a commercial) for learning and also working purposes, it handles namespaces and finds FQP quite well, it will save you a lot of time. – biesior May 19 '21 at 19:27
  • yes, I noticed that when watching laracasts. I'm using VS Code and was actually quite happy with it. My entry barrier to PhpStorm was the price so far... – Wondarar May 19 '21 at 19:29

0 Answers0