We help IT Professionals succeed at work.

Undefined variable problem

Robert Francis
on
166 Views
Last Modified: 2017-03-09
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?
Comment
Watch Question

gr8gonzoConsultant
CERTIFIED EXPERT

Commented:
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);
Consultant
CERTIFIED EXPERT
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Robert FrancisDirector of Continuous Improvement

Author

Commented:
Would I not have to do the same thing for $connectionInfoIntranet?
Robert FrancisDirector of Continuous Improvement

Author

Commented:
Oops, we commented at the same time
Robert FrancisDirector of Continuous Improvement

Author

Commented:
Thanks for the lesson.