Search code examples
phpautoloader

Namespaces and Static Methods in PHP


I'm using PHP 5.5 and I'm trying to use the AWS-SDK for PHP.

Here is how my code looks like:

require_once 'AWS/aws.phar';

use Aws\DynamoDb\DynamoDbClient;


DynamoDBAccessLayer::init();


class DynamoDBAccessLayer {

    public static $client;

    public static $AWSCredentials = array(
        'region' => 'us-east-1',
        'key' => 'KEY',
        'secret' => 'SECRET'
    );

    public static function init() {
        self::$client = DynamoDbClient::factory(self::$AWSCredentials);
    }
}

All I'm trying to do at this point is initiate the client, but there are namespace related problems, the following error is thrown when init() is executed:

PHP Fatal error:  Class 'Aws\DynamoDb\DynamoDbClient' not found in....

The reason I know this is a name space issue is that the following code does assign client properly without errors:

require_once 'AWS/aws.phar';

use Aws\DynamoDb\DynamoDbClient;

DynamoDBAccessLayer::$client = Aws\DynamoDb\DynamoDbClient::factory(DynamoDbAccessLayer::$AWSCredentials);

class DynamoDBAccessLayer {

    public static $client;

    public static $AWSCredentials = array(
        'region' => 'us-east-1',
        'key' => 'KEY',
        'secret' => 'SECRET'
    );
}

So PHP can access DynamoDbClient class outside of these static methods, but can't access it inside them.

How can I make Aws\DynamoDb\DynamoDbClient accessible inside the init() static method?


Solution

  • I was able to solve this issue with the following code:

    require './aws-autoloader.php';
    use \Aws\DynamoDb\DynamoDbClient;
    
    $client = \Aws\DynamoDb\DynamoDbClient::factory(array(
        'profile' => 'default',
        'region' => 'us-east-1',
        'base_url' => 'http://localhost:8000'
    ));
    
    echo "<pre>";
    var_dump($client);
    echo "</pre>";
    

    Let me know if you have any questions/problems.