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?
PHP

Avatar of undefined
Last Comment
Robert Francis

8/22/2022 - Mon
gr8gonzo

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
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Robert Francis

ASKER
Would I not have to do the same thing for $connectionInfoIntranet?
Robert Francis

ASKER
Oops, we commented at the same time
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Robert Francis

ASKER
Thanks for the lesson.