Getting PHP variables from an include

Published on 2020-07-25 • Modified on 2020-07-25

In this snippet, we will see how to get a variable from an include. Here, we affect the return value of an include call to the $deployClass variable, so, the include must return something. In this case, the deploy.php file, which is the file used to deploy this website on my VPS server returns return new class extends DefaultDeployer. You can find the full code of this file in this snippet.


<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet105Trait.php

namespace App\Controller\Snippet;

use Symfony\Component\HttpKernel\KernelInterface;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property KernelInterface $kernel
 */
trait Snippet105Trait
{
    public function snippet105(): void
    {
        $deployClass = include $this->kernel->getProjectDir().'/config/prod/deploy.php';

        echo get_parent_class($deployClass); // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  More on the web

<?php declare(strict_types=1);

namespace App\Tests\Controller\Snippets;

use EasyCorp\Bundle\EasyDeployBundle\Deployer\DefaultDeployer;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @covers Snippet105Trait
 */
final class Snippet105Test extends KernelTestCase
{
    protected function setUp(): void
    {
        self::bootKernel();
    }

    /**
     * @covers Snippet105Trait::snippet105
     */
    public function testSnippet105(): void
    {
        $deployClass = include self::$kernel->getProjectDir().'/config/prod/deploy.php';
        self::assertInstanceOf(DefaultDeployer::class, $deployClass);
    }
}