Link to home
Create AccountLog in
Avatar of Robert Francis
Robert Francis

asked on

Undefined variable problem

Just starting to learn oo php. Probably a simple problem.

Here is some of the code from header.php

$serverName = "server\\exactsqlexpress"; 
$connectionInfoIntranet = array( "Database"=>"intranet", "UID"=>"???", "PWD"=>"???");
$connectionInfoPpp = array( "Database"=>"ppp", "UID"=>???", "PWD"=>"???");

Open in new window


Here is some of the code from dbIntranet.php
include("header.php");

class dbIntranet {

	private $connIntranet;
	
	function __construct(){
			$this->open_connection();
	}
	
	public function open_connection() {
			$this->connIntranet = sqlsrv_connect($serverName, $connectionInfoIntranet); <-----LINE 13
	}

Open in new window


I keep getting an error:

Notice: Undefined variable: serverName in C:\inetpub\wwwroot\portal2\inc\dbIntranet.php on line 13

What's up?
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

header.php is defining $serverName in the global scope. Code inside of a function or a class method can't see the global scope automatically - they only see the variables that are passed in or otherwise made explicitly available to them.

So you -could- do this to your class definition:
class dbIntranet {

      private $connIntranet;
      private $serverName; // New class property called serverName
      
      function __construct($serverName){ // Change the constructor to accept a new parameter
                 $this->serverName = $serverName; // Copy the value of the parameter to the class property
                  $this->open_connection();
      }
      
      public function open_connection() {
                  $this->connIntranet = sqlsrv_connect($this->serverName, $connectionInfoIntranet); <-----LINE 13
      }

...and then when you created a new instance of dbIntranet, you pass in your global variable:

$x = new dbIntranet($serverName);
ASKER CERTIFIED SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of Robert Francis
Robert Francis

ASKER

Would I not have to do the same thing for $connectionInfoIntranet?
Oops, we commented at the same time
Thanks for the lesson.