Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active April 25, 2018 11:59
Show Gist options
  • Save tommcfarlin/c835d263062e768980d5ad3f6941f60e to your computer and use it in GitHub Desktop.
Save tommcfarlin/c835d263062e768980d5ad3f6941f60e to your computer and use it in GitHub Desktop.
[PHP] A Primer On Reflection in PHP (And How It Plays Into Unit Testing)
<?php
namespace Acme\Plugin;
class APIClient
{
private $username;
// Other functions for class implementation...
}
<?php
namespace Acme\Plugin\Tests;
use Acme\Plugin\API\APIClient;
class APIClientTest
{
public function setUsername()
{
// Instantiate the class.
$client = new APIClient();
$username = 'tommcfarlin';
$client->setUsername($username);
// Now get a reflected instance of the class.
$reflectedClient = new ReflectionClass('Acme\Plugin\API\APIClient');
// More to come...
}
}
<?php
namespace Acme\Plugin;
class APIClient
{
private $username;
public function setUsername($username)
{
$this->username = $username;
}
// Other functions for class implementation...
}
<?php
namespace Acme\Plugin\Tests;
use Acme\Plugin\API\APIClient;
class APIClientTest
{
public function setUsername()
{
// Instantiate the class.
$client = new APIClient();
$username = 'tommcfarlin';
$client->setUsername($username);
// Now get a reflected instance of the class.
$reflectedClient = new ReflectionClass('Acme\Plugin\API\APIClient');
$usernameProperty = new ReflectionObject($client);
$usernameProperty->setAccessible(true);
// More to come...
}
}
<?php
namespace Acme\Plugin\Tests;
use Acme\Plugin\API\APIClient;
class APIClientTest
{
public function setUsername()
{
// Instantiate the class.
$client = new APIClient();
$username = 'tommcfarlin';
$client->setUsername($username);
// Now get a reflected instance of the class.
$reflectedClient = new ReflectionClass('Acme\Plugin\API\APIClient');
// Grab a reference to the private property by making it accessible.
$usernameProperty = new ReflectionObject($client);
$usernameProperty->setAccessible(true);
// And finally, read it's value.
$usernameValue = $usernameProperty->getValue($client);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment