Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin tommcfarlin/00-apiClient.php Secret
Last active Apr 25, 2018

Embed
What would you like to do?
[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
You can’t perform that action at this time.