faker in php code example

Example: php faker

Installation#
Faker requires PHP >= 7.1.


composer require fakerphp/faker
Basic Usage#
Autoloading#
Faker supports both PSR-0 as PSR-4 autoloaders.


// when installed via composer
require_once 'vendor/autoload.php';
You can also load Fakers shipped PSR-0 autoloader


// load Faker autoloader
require_once '/path/to/Faker/src/autoload.php';
alternatively, you can use any other PSR-4 compliant autoloader

Create fake data#
Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by calling methods named after the type of data you want.


require_once 'vendor/autoload.php';

// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();
// generate data by calling methods
echo $faker->name();
// 'Vince Sporer'
echo $faker->email();
// '[email protected]'
echo $faker->text();
// 'Numquam ut mollitia at consequuntur inventore dolorem.'
Each call to $faker->name() yields a different (random) result. This is because Faker uses __call() magic, and forwards Faker\Generator->$method() calls to Faker\Generator->format($method, $attributes).


for ($i = 0; $i < 3; $i++) {
    echo $faker->name() . "\n";
}

// 'Cyrus Boyle'
// 'Alena Cummerata'
// 'Orlo Bergstrom'

Tags:

Php Example