Jump to content

Help with including a file


Darkmatter5

Recommended Posts

config.php is in "public_html/library"

funcs.php is in "public_html/library"

index.php is in "public_html"

 

Here's config.php

<?php
  $admin_email="****";
  $url="http://www.mysite.com";
  $dbhost="localhost";
  $dbuser="user";
  $dbpass="pass";
  $dbname="name";
?>

 

Here's funcs.php

<?php
  class werb {
    function page_theme() {
      include_once('config.php');
      echo "dbhost: $dbhost";
    }
  }
?>

 

Here's index.php

<?php
  include('library/config.php');
  require_once('library/funcs.php');
  $werb=new werb();
  $werb->page_theme();
?>

 

All I get from loading index.php is:

dbhost:

 

It should be:

dbhost: localhost

 

What's wrong?

Link to comment
https://forums.phpfreaks.com/topic/160067-help-with-including-a-file/
Share on other sites

You need to get GLOBAL variables

 

<?php

  class werb {

    function page_theme() {

      include_once('config.php');

      echo "dbhost: $dbhost";

    }

  }

?>

should be

<?php

  class werb {

    function page_theme() {

global $dbhost;

      include_once('config.php');

      echo "dbhost: $dbhost";

    }

  }

?>

Perhaps the user's theme is stored in their database profile?

 

You're going to get confused with all those variables floating around the global namespace.  You'd be better off creating a singleton class called MyConfig that reads your config.php file and loads members with the config values.  Also, you might as well make your config.php a config.ini file and just use PHP's parse_ini_file() function.

 

/* index.php */
require_once( 'classes/MyConfig.php' );

include( 'somefile.php' );

 

/* somefile.php */

function a_random_func() {
  $cfg = MyConfig::getInstance();
  echo 'dbhost: ' . $cfg->dbhost . "\n";
}

Probably.  But since he's learning...

 

Consider setting up the MyConfig singleton as I suggested.

 

I also like to use a Database singleton that returns a handle to a PDO object.  Then I can just do:

<?php
$pdo = Database::getPDO();
?>

 

<?php
/* Database.php */
class Database {
  static private $_pdo = false;
  static public function getPDO() {
    if( self::$_pdo === null ) {
      $cfg = MyConfig::getInstance();
      $pdo = new PDO( /* fill this in */ );
      if( $pdo instanceof PDO ) {
        self::$_pdo = $pdo;
      }else{
        throw new Exception( "PDO creation." );
      }
    }
    return self::$_pdo;
  }
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.