How to share an instance through several php a-la-Wordpress files?

Greetings to all

I am currently using Wordpress as my CMS and am using the Facebook API for the user account / registration "stuff".

My question is: how to use the PHP PHP SDK (here: http://github.com/facebook/php-sdk/ ) when Wordpress compiles several php files to output a single web page? In other words, Wordpress templates header.php + index.php + footer.php = what you see on www.example.com

If I create my own instance of the Facebook application in HEADER.PHP , how do I link to them in INDEX.PHP and FOOTER.PHP

Thanks in advance!

----- SAMPLE CODE ---

in header.php

<?php
require '/facebook.php';

// Create our Application instance.
$facebook = new Facebook(array(
  'appId' => 'xxx',
  'secret' => 'xxx',
  'cookie' => true,
));
?>

in index.php

<?php
$session = $facebook->getSession();
?>
+3
source share
4 answers

If you install $facebookin header.php, you wo n’t be able to access it in index.phpunless you started it.

This is due to the fact that it is header.phploaded through a function get_header()that narrows the scope of all non-global variables.

So, you can either globalize $facebook OR , since you need one instance Facebook, I highly recommend using the helper function singleton ;

function get_facebook_instance()
{
    static $f;
    if (!isset($f)) {
        if (!class_exists('Facebook'))
            require('/facebook.php');
        $f = new Facebook(array(
            'appId' => 'xxx',
            'secret' => 'xxx',
            'cookie' => true,
        ));
    }
    return $f;
}

Note. If you are using PHP5, you do not need to worry about returning by reference.

+3

facebook header.php :

$facebook = new Facebook('API', 'SECRET');

facebook $facebook index.php footer.php , .php.

+1

PHP , , header.php index.php. , - :

index.php

<?php
// blah blah other code
$session = $facebook->getSession();
// blah blah more code
include('header.php');

, , :

<?php
// blah blah other code
$session = $facebook->getSession();
// blah blah more code
require '/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
  'appId' => 'xxx',
  'secret' => 'xxx',
  'cookie' => true,
));

, , $facebook .

var_dump($facebook); header.php( , $facebook, index.php( , $facebook).

, , , Facebook Graph API false - . var_dump , $facebook ( - ), , $facebook ( NULL E_NOTICE, - Facebook - , API Facebook Graph).

+1

Wordpress Facebook Connect Plugin, .

0

Source: https://habr.com/ru/post/1754078/


All Articles