douwei1174 2016-10-20 06:20
浏览 92

faker $ generator属性如何允许我们调用其他提供者的格式化程序

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

  • 写回答

1条回答 默认 最新

  • douhoulei4706 2016-12-09 16:21
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题