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);
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
{
/** @noinspection UsingInclusionReturnValueInspection */
$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\Integration\Controller\Snippets;
use EasyCorp\Bundle\EasyDeployBundle\Deployer\DefaultDeployer;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
/**
* @see Snippet105Trait
*/
final class Snippet105Test extends KernelTestCase
{
/**
* @see Snippet105Trait::snippet105
*/
public function testSnippet105(): void
{
self::bootKernel();
$deployClass = include self::$kernel->getProjectDir().'/config/prod/deploy.php';
self::assertInstanceOf(DefaultDeployer::class, $deployClass);
}
}
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
