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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用