Get all the methods in a class

By using the getMethods() function from ReflectionClass you are able to get all the methods in a class.

Simply create an object of the ReflectionClass with one argument, the class name you want to access. Then, use the getMethods() function and assign the result to a variable.

$class_obj = new ReflectionClass('myClass');
$array_of_methods = $class_obj -> getMethods();
var_dump($array_of_methods);

Check if the class method exists in PHP

You can simply use the built-in function method_exists() and it will return a boolean true if it exists and false if it doesn’t.

Example Usage:

$class_obj = new ClassName();
var_dump( method_exists($class_obj, 'myMethodName') );

Example Output:

bool(true)

Getting API response with authentication

Oftentimes, file_get_contents() function comes really handy when we are trying to pull data from an API. We can simply do it by doing this:

$json_data = file_get_contents('http://theurl.com/api/json');

But what if the API requires authentication? Then, you’ll need a way to communicate with the authenticated server or else the server will give you this response.

Warning: file_get_contents(http://www.yourdomain.com/file.php): failed to open stream: HTTP request failed! 
HTTP/1.1 401 Authorization Required in file.php on line 7

In order to avoid that, first we need a way to add the username and password to the HTTP header in the request. We can simply use the stream_context_create() function.

Next is to use that stream context in the file_get_contents() function as the third parameter. As for the second parameter, just simply use false or 0 to skip it.


$username = 'theusername';
$password = 'thepassword';

$context = stream_context_create(array(
  'http' => array(
    'header' => "Authorization: Basic " . base64_encode("$username:$password")
  )
));

$json_data = file_get_contents('https://theurl.com/api/json', false, $context);

http://www.hashbangcode.com/blog/using-authentication-and-filegetcontents