I have a class and defined as follows:

class theclass
{ var a;
var b;


function seta(x)
{this->a=x;
}

function setb(x)
{this->b=x;
}

}

global $myclass;
$myclass=new theclass;

This is saved in a fileone.php

Then I use it in the fisrt script file as

include_once("fileone.php");
global $myclass;
$myclass->seta(7);
includeonce("filethree.php");

this one is saved as filetwo.php.

My question is on using this class in filethree.php and filefour.php as follows:


Suppose that my filethree.php is

global $myclass;
myclass->setb(8);
$Z=$myclass->a+$myclass->b;

I will get a Fatal error: Call to a member function a on a non-object.

To avoid this error, I would do filefour.php as follows

include_once("fileone.php");
global $myclass;
myclass->setb(b);
$Z=$myclass->a+$myclass->b;

I would avoid a fatal error but would get a less sever error that calling a member value a that has not been set, or something like that althought I know that I set "a" in filetwo.php

Questions:

(1) Since I declared my class as global in all files, I would expect that all script files will see it and I only need to declare it in the first script file that calls it, in this case filetwo.php after which filethree.php would have seen it without having to include-once again.

(2) If I include_once it in filefour.php, does it mean that the member variable set by filetwo.php will be replaced or destroyed?

this should be $this
myclass should $myclass

note that variables are preceded by a $

this should be $this
myclass should $myclass

note that variables are preceded by a $

TYes I see it; however, it is a minor typographic error that could have been caused by typing the code in this forum without testing it. In the real program these syntactic errors are not there since they are normally detected on runtime.

This syntactic error does not answer my question, however, which is on how to use classes in programs.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.