I am still new to programming and learning OOP. I have recently discovered how to make classes in PHP and how to access them. Before I describe the issues, I can easily make workarounds but I am making every stride to implement/learn to code in a professional manner and using DRY code.
The issue I am encountering is trying to access a single Object which I aim to use in other php files, while the user is logged in. For instance, the user will enter their credentials to log in, this will initialize a "User" object used to verify the password. Once verified the user is redirected to another php file/page. However, at this point, I am finding that the Object is destroyed and I do not have access to the initial one created in that first step. (it returns null)
I know I am still learning, but creating more than one object for the same user sounds like a waste of resources to me and does not follow DRY code.
I created a php file (test.php) which is used to enter the login credentials, that check a local PHP DB. If the credentials are found the user is redirected to another page (test2.php).
On the redirect page (test2.php) I have included access to the same file and also attempt to call a method on the initialized object.
<?php
include 'classes/connection.class.php';
include 'includes/sql.inc.php';
include 'classes/userfuncs.class.php';
$user;
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$user = new User();
$loginStats = $user -> verifyAcct($email, $pwd);
if($loginStats['acctVerified']) {
header("location: test2.php");
} else {
header("location: test.php");
}
}
<?php
//test2.php
require "userobj.inc.php";
$user->page1Msg();
?>
After entering proper credentials at the login page (test.php), I am successfully being redirected to the 2nd page (test2.php) however I am given an "Undefined variable" message which lets me know that I am unable to access that initial object. I expect a simple echo message to be displayed from the method called on that 2nd page, however, that message will only display if the Object still exists or is recreated. Again, I am unsure if this is proper code practice, but I do not wish to recreate the object.
The message being given is:
Notice: Undefined variable: user in /Applications/XAMPP/xamppfiles/htdocs/tutorials/php/IEX-Update/test2.php on line 3
Fatal error: Uncaught Error: Call to a member function page1Msg() on null in /Applications/XAMPP/xamppfiles/htdocs/tutorials/php/IEX-Update/test2.php:3 Stack trace: #0 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/tutorials/php/IEX-Update/test2.php on line 3