0

I am new to faker and also quite new to PHP. My question is rather towards how PHP works. For my question, I take Faker (a PHP library that generates fake data) as an example. For reference the url is:

https://github.com/fzaninotto/Faker#faker-internals-understanding-providers

I was reading through the faker internals documentation and saw this code:

 <?php

namespace Faker\Provider;

class Book extends \Faker\Provider\Base
{
  public function title($nbWords = 5)
  {
    $sentence = $this->generator->sentence($nbWords);
    return substr($sentence, 0, strlen($sentence) - 1);
  }

  public function ISBN()
  {
    return $this->generator->ean13();
  }
}

What I am curious at is the ISBN method. It basically uses the $generated protected property of its base class to call a method named ean13(). But the arrow sign is usually used to call a method or get a variable within an object. I understand that $generator is an object of the class Generator as it was defined in the constructor like so:

    class Base
{
    /**
     * @var \Faker\Generator
     */
    protected $generator;

    /**
     * @var \Faker\UniqueGenerator
     */
    protected $unique;

    /**
     * @param \Faker\Generator $generator
     */
    public function __construct(Generator $generator)
    {
        $this->generator = $generator;
    }

But then I don't know where the program goes to find method ean13(). I opened the Generator class and find no method of that name. I was hoping for developers experienced in PHP to explain how it actually works to me. Thanks

Rendy Tan
  • 1
  • 1

1 Answers1

1

You've stumbled upon usage of what PHP calls "method overloading". (Note that "method overloading" has different meaning in other languages). PHP Doc for method overloading

If you check the source code for the Generator class, you'll find a method in it called __call(). What this does is catch all method calls to non-existing methods in the Generator class. That method in turn calls the format method which does a lookup against the available formatters, in this case ean13, found in the Barcode class.

This is how you can write and load your own formatters, and do things like

$faker->my_own_format()

without having to touch the Generator class itself.

Community
  • 1
  • 1
Ulrik
  • 493
  • 2
  • 16