mysqli - why is this php variable undefined -


Can anyone tell me why this does not work.

  class class1 {Private $ database; Function class1 () {$ database = $ this- & gt; Connect (); } Private Function Connect () {$ database = mysqli_connect ("localhost", "user name", "", "db"); If (mysqli_connect_errno ()) {echo "failed to connect to MySQL:". Mysqli_connect_error (); } $ Returned the database; } Private function usedb () {$ query = "Some SQL"; Mysqli_query ($ database, query $); }}   

I hope this simple example can clearly demonstrate my problem adequately. Anyway, when I run something like this, I see an error that tells me that the "ezardb ()" function references an undefined variable "database". As if out of the scope of the variable ... can anyone give me a solution?

This is because in class1 () you can add another local variable < Via code> $ databases :

  $ database = $ this- & gt; Connect ();   

To set and access the $ database property you should use:

  $ this- & Gt; Database = $ this- & gt; Connect ();   

same function:

  Personal function is used () {$ query = "some sql"; Mysqli_query ($ this- & gt; database, $ query); }   

So your last code should look like this:

  class class1 {Private $ database; Function class1 () {$ this-> Database = $ this- & gt; Connect (); } Private Function Connect () {$ database = mysqli_connect ("localhost", "user name", "", "db"); If (mysqli_connect_errno ()) {echo "failed to connect to MySQL:". Mysqli_connect_error (); } $ Returned the database; } Private function usedb () {$ query = "Some SQL"; Mysqli_query ($ this- & gt; database, $ query); }}   

Note:

The same applies to $ databases in connectivity ( ) function. Although with the same name, it does not do anything with the $ database variable outside, because it should be used for $ this-> database (if necessary)

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

.net - Creating a new Queue Manager and Queue in Websphere MQ (using C#) -