PHP: resolving types in different files/namespaces

青春壹個敷衍的年華 提交于 2019-12-13 06:25:42

问题


I am trying to write a PHP client for a Thrift server written in C. I am following the tutorial given at http://chanian.com/2010/05/13/thrift-tutorial-a-php-client/.

I am very new to PHP and, I suspect, am missing some of the language fundamentals.

The code in question is:

<?php 
// Setup the path to the thrift library folder
$GLOBALS['THRIFT_ROOT'] = 'Thrift';

// Load up all the thrift stuff
require_once $GLOBALS['THRIFT_ROOT'].'/Thrift.php';
require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TSocket.php';
require_once $GLOBALS['THRIFT_ROOT'].'/transport/TBufferedTransport.php';

// Load the package that we autogenerated for this tutorial
require_once $GLOBALS['THRIFT_ROOT'].'/packages/encabulationgame/EncabulationGame.php';

// Several things might go wrong
try {
    // Create a thrift connection (Boiler plate)
    $socket = new TSocket('localhost', '65123'); <--error is here

I am getting an error "Class 'TSocket' not found in /var/www/foo/scores.php on line 22"

TSocket is defined in Thrift/transport/TSocket.php. The Thrift/transport/TSocket.php file (with comments removed) reads:

<?php

namespace Thrift\Transport;

use Thrift\Transport\TTransport;
use Thrift\Exception\TException;
use Thrift\Exception\TTransportException;
use Thrift\Factory\TStringFuncFactory;

/**
 * Sockets implementation of the TTransport interface.
 *
 * @package thrift.transport
 */
class TSocket extends TTransport {

If I change my code to:

 $socket = new Thrift\Transport\TSocket('localhost', '65123');

Then my code (well, this line, at least) no longer throws an error. I'm curious: what did the author of this tutorial do to get this code to work on his system that I'm not doing on my system?

Secondly, I attempted to solve the problem by adding the line:

use Thrift\Transport;

to my file before I create $socket, but that didn't solve the problem as I'd expected it to.

How do I convince PHP to resolve this type that's defined in another file? (There are several types in several files that I have to resolve.)


回答1:


PHP does not import an entire namespace, instead you must "use" each namespaced class you wish to import. Instead of use Thrift\Transport; write

use Thrift\Transport\TSocket;

This is described in more detail in the manual under Using Namespaces: Aliasing/Importing. Is it possible that the article was written before Thrift was namespaced?



来源:https://stackoverflow.com/questions/16141791/php-resolving-types-in-different-files-namespaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!