简体   繁体   中英

Facebook PHP SDK 4.0: using classes in subsites

I think this is very simple for many of you, but in the moment I got stuck with this. I have the following part of code:

header.php

include "facebook/autoload.php";

use Facebook\FacebookRedirectLoginHelper;

test.php

include "header.php";
$helper = new FacebookRedirectLoginHelper($redirect_url);

Why do I always get this error:

Fatal error: Class 'FacebookRedirectLoginHelper' not found in test.php on line

I thought when I include a PHP file, classes can also be used. But in this case not, why? I think I do not understand how this autoload and use works, so I would be happy for some explanation.

PHP does not inherit the namespaces nor the use statements of included/required files. This is intentional as otherwise if you include 2 files using a class aliased the same way you will get errors and you might not need all those classes in firs place.

If a class requires a namespace it has to have use statement defined with the full namespace to the particular class they need. Except in the cases where there might be aliasing. For example if you have:

// file1.php
use \My\Cool\LogWriter as Writer;

and

// file2.php
use \My\Cool\FileWriter as Writer;

Now both classes are accessible as Writer .

// test.php
require 'file1.php';
require 'file2.php';

In which case if you don't declare which class from which space you want this will give nasty error that class Writer is defined, which is true, but it is also true that the two classes are 2 separate ones.

For more information on namespaces in PHP5 see ( http://php.net/manual/en/language.namespaces.php ).

As a side note:

  • Every file, if not namespace declaration is provided is considered in the global namespace.
  • If a use is without leading slash the namespace might be considered relative to the current. (unsure but I think it depends on the autoloader?) (Reference here: https://stackoverflow.com/a/4879615/1747193 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM