Call to undefined function isLoggedIn() - php

I do not understand why the isLoggedIn(); function isn't defined according to the error I am receiving. I have two pages one is a .php where functions are defined and a .phtml where I am having the issue. Below is the code for both.
public function isLoggedIn() {
if(!session_id()) {
return false;
}
else
{
return true;
}
}
Above is on the .php, which shows its function.
<?php
$is_logged_in = isLoggedIn();
if($is_logged_in) {
echo '<li>Logout</li>';
}
else {
echo '<li>Login</li>';
}
?>
Above is on the .phtml, which should work, as far as I am aware.
The very top of the .phtml document has
<?php require ('Models/SessionData.php');
Which is the name and location of the functions definition.
On the IDE there is no sign of anything being wrong.
Help would be appreciated.

As I explained in the comments, it looks like isLoggedIn() is part of a class (hence the public keyword). You cannot simply call object methods on their own (unless they're static). You'll need to instantiate a new object of whatever type the class is.
It seems that isLoggedIn() just checks session_id(), so you could easily extrapolate that into your code and simplify the whole thing. Your PHTML snippet could be rewritten using a ternary operator as:
echo (session_id()) ? '<li>Logout</li>' : '<li>Login</li>';
That having been said though, the method's probably in a class for a reason.

remove the word public.
function isLoggedIn() {
if (!session_id()) {
return false;
} else {
return true;
}
}
although you should probably follow the advice of others and look into classes

isLoggedIn() is a public function meaning that you must use an object to access that function. (OOP)
To call fhe function, an object of SessionData must exist:
Example:
$session = new SessionData();
$is_logged_id = $session->isLoddedIn();
Check for the object in your included scripts, it could have been already instantiated (some global variable).

change it to
class logging{
public function isLoggedIn() {
if(!session_id()) {
return false;
}
else
{
return true;
}
}
}
and then change the other part to
$is_logged_in = new logging;
if($is_logged_in->isLoggedIn()) {
That should work

Related

PHP function working differently for return and echo. Why?

By using the following class:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
$trimmed=trim($form);
$specialchar=htmlspecialchars($trimmed);
$finaloutput=stripslashes($specialchar);
echo $finaloutput;
}
public function __destruct()
{
unset($finaloutput);
}
}
and Calling the function, by the following code, it works fine.
<?php
require('source/class.php');
$target="<script></script><br/>";
$forminput=new SafeGuardInput($target);
?>
But if in the SafeGuardInput class if I replace echo $finaloutput; with return $finaloutput; and then echo $forminput; on the index.php page. It DOES NOT WORK. Please provide a solution.
You can't return anything from a constructor. The new keyword always causes the newly created object to be assigned to the variable on the left side of the statement. So the variable you've used is already taken. Once you remember that, you quickly realise there is nowhere to put anything else that would be returned from the constructor!
A valid approach would be to write a function which will output the data when requested:
class SafeGuardInput{
public $form;
public function __construct($form)
{
$this->form=$form;
}
public function getFinalOutput()
{
$trimmed = trim($this->form);
$specialchar = htmlspecialchars($trimmed);
$finaloutput = stripslashes($specialchar);
return $finaloutput;
}
}
Then you can call it like in the normal way like this:
$obj = new SafeGuardInput($target);
echo $obj->getFinalOutput();

Call a session inside a function with object oriented php

I'm new to oop and some lines of my code are only approximate, to indicate what I want to achieve.
I want to create a session with php within a function within a class and call it in another function.
class My_beautiful_class
{
public function index()
{
$_SESSION['ciao'] = 'ciao';
var_dump($_SESSION);
}
public function anotherfunction()
{
$this->index();
var_dump($_SESSION);
}
}
I just want to understand a concept: in this way, my code will work but, on the other end, it will execute everything it will find in my function index, in my other function anotherfunction. So, if I call two variable with the same name, I could have a problem.
I guess that in theory, I could handle the problem in another way which is that I could create a variable call sessionone for example and send it some values in with my index function:
class My_beautiful_class
{
public sessionone = [];
public function index()
{
$_SESSION['ciao'] = 'ciao';
$this->sessionone = $_SESSION['ciao'];
}
public function anotherfunction()
{
$this->sessionone;
var_dump($_SESSION);
}
}
, but I was wondering if there any way to for example call only one variable that lives in one function with my first approach.
Something like: (My code is wrong on purpose, it is only to indicate what I want to achieve)
public function index()
{
$_SESSION['ciao'] = 'ciao';
}
public function anotherfunction()
{
$this->index( $_SESSION['ciao'] );
}
}
The $_SESSION variable are what is called a Superglobal in PHP: http://php.net/manual/en/language.variables.superglobals.php This gives them a few unique traits.
First, Superglobals are accessible anywhere in your application regardless of scope. Setting the value of a superglobal key in one function will make the value accessible anywhere else in your application that you want to reference it.
Say for example we want to make a class to manage our session. That class may look something like this.
class SessionManager
{
public function __construct()
{
session_start(); //We must start the session before using it.
}
//This will set a value in the session.
public function setValue($key, $value)
{
$_SESSION[$key] = $value;
}
//This will return a value from the session
public function getValue($key)
{
return $_SESSION[$key];
}
public function printValue($key)
{
print($_SESSION[$key]);
}
}
Once we have a class to manage it a few things happen. We can use this new class to add info to the session and also to retrieve it.
Consider the following code:
$session = new SessionManager();
$session->setValue('Car', 'Honda');
echo $session->getValue('Car'); // This prints the word "Honda" to the screen.
echo $_SESSION['Car']; //This also prints the word "Honda" to the screen.
$session->printValue('Car'); //Again, "Honda" is printed to the screen.
Because of a session being a superglobal, once you set a value on the session it will be assessable anywhere in your application, either in or outside of the class itself.
You must call session_start() at the beginning of your class.
You can also start the session at the beginning of your code if you include your class like this sample
Remember that you can call the session_start only one time

Is having the entire function body inside an if statement considered bad practice?

I often find myself writing functions which look like:
public function foo($param): void
{
if($param) {
//do something
}
}
with no code executing if $param evals to false.
This looks like a bad practice, are there any guidelines/patterns on how to avoid this kind of coding?
Add access modifiers to function
Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.
public function foo($param=null)
{
/* Condition while not empty then proceed */
if(!empty($param)) {
//do something
} else {
return false;
}
}
It depends on what you want to do with the function.
But my opinion is your condition should be outside of the function, for example
function foo() {
// doing something
}
and then
if ($params) {
foo();
}
it would look more customizable
You can improve the function like this:
function foo($param='defaultValue')
{
if($param)
{
//do something
return true; // or something else
}
return false; // by default return false
}
By doing this, if $param will be evaluated as false, the return false will be used.
Also, in case your function is inside a class, it's best practice to specify an access modifier (public, protected, private) for that function.
Personally I'd change this code to:
function foo($param)
{
$param
&& (function () {
// Do code here.
})();
}
but then if I wanted to call the inner function elsewhere, and keep everything clean, I'd probably refactor it into this:
function foo($param)
{
$param
&& bar();
}
function bar()
{
// Do code here
}
Then I'd adjust the naming of foo to make it clear that it's a wrapper over bar and rename bar so that it sounds like it's missing the wrapper, maybe something like action_only or action_without_foo
Then I'd also write it up in the dochints for each function, in OOP land this would be a private method, but that doesn't enforce true privacy either see: What is the point of OOP visibility in PHP when Closures and Reflections are available?, in fact the closure inside the function, in the first example, is more "private" on a technical level
If a function is an all-or-nothing condition, I have the else condition first - this way, if the $param resolves as false the function quits immediately:
public function foo($param): void
{
if(!$param) {
return;
}
//do something
}

PHP - class forget set variables

I try to create some sort of setup class, like global values for the page.
The PHP-code
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
Question
My class forget the value I set. Why is that?
Do I have to use global variables?
Is this the correct approach for the problem?
The variable is set on an object, not on a class.
For each class, you can instantiate multiple objects. Each of those have their own variable scope.
Edit:
I forgot to include the easiest, and least verbose solution to your problem. AFAIK, you're looking for a way to check what page you're on. Constants will do just that:
defined('MY_CURRENT_PAGE') || define('MY_CURRENT_PAGE','My Value');
//use anywhere like so:
echo 'Currently on page: '.MY_CURRENT_PAGE;
My class forget the value I set. Why is that?
Quite simple: your page member function isn't static, yet you call it as though it is: get::page(). Even if you were to fix this, you're creating a new instance in the page method, but you're not preserving a reference too it anywhere, so each page call will create a new globals instance, that has nothing set.
Do I have to use global variables?
No, unless you're Really desperate, never use globals
Is this the correct approach for the problem?
No, if it doesn't work, it's not correct (IMHO).
Well, what is, you might ask. There are several ways to go about this:
class globals
{
public static $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
private $_globalsInstance = null;
public function __construct(globals $instance = null)
{
$this->_globalsInstance = $instance;
}
private function _getGlobals()
{
if (!$this->_globalsInstance instanceof globals)
{
$this->_globalsInstance = new globals();
}
return $this->_globalsInstance;
}
public function page()
{
return $this->_getGlobals()::$page;
}
}
Personally, however, I wouldn't work like this, I'd just pass my instances to wherever I need them (as arguments to functions/methods or just instantiate them in a scope that will be accessible:
class globals
{
public $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
$page = new globals();
$page->set_page('foobar');
someFunction($page);
$someObject->renderPage($page);
require_once('specificScript.php');
//inside required script:
echo $page->page;
Do I have to use global variables?
Not, if your can use PHP 5.3
Is this the correct approach for the problem?
Better to use a generic class for this, or use static properties of objects
<?php
class globals
{
public static $page;
public function __construct()
{
}
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
public static function page()
{
return globals::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
P.S.
But this is not a nice approach
$globals there
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
and there
$globals = new globals();
$globals->set_page('My value');
are different inctances of globals class.
One of the solutions is to make $page var static
public static $page;
I hope this helps
UPD:
Also you might apply Singleton to globals class and request for its insnance instead of creating new one directly:
globals::getInstance()->setPage('Page');
and
return globals::getInstance()->getPage();
In this case $page doesn't have to be static.
I'm not sure the other answers are very clear. You have created 2 classes. As such they have different scopes. As writen you can't access the original variable $page from the get class because it's outside the scope. Your page function in fact creates a new version of the object $globals without $page set. Normally you would place both your set and get functions in the initial object/class. Though it would be possible to use two class by calling the first class from the second and setting the page. Why you would want to do that I'm not sure.
if I were writing the class it would look like this.
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
public function get_page()
{
return $this->page;
}
}
Actually I would probably set page to private not public. As public I guess you don't need a get function.
for using methods of the class without object you must use static definition. but anyway you put value for one class object and try to get it from another...
Perhaps this will help you continue on your coarse:
class globals
{
public static $page;
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get extends globals
{
public function page()
{
$globals = new globals();
return parent::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page();
?>

Validity of php variables

It may sound silly but I'm quite php outdated/unexperienced and coming from Java programming back to php, so I mix up the concepts.
If in a php webpage I declare a variable
$debug=TRUE;
and try to access it from below within a function
a(){
if ($debug){
echo "I'm here";
}
}
the variable doesn't exists or isn't initiated? The whole file is just simply:
<?php
$debug=TRUE;
a(){
if ($debug){
echo "I'm here";
}
}
?>
Do I need to make a session variable or something else? I'm quite clueless & the same concept is confusing me for the use of other variables within. Also for the further use of variables, I am trying to be forced to pass all the variables I need forward to the function where I use them and a class concept as in Java perhaps would be cleaner but is a kind of too much for this simplicity. Or do I need the functions (it's a form processor) to be declared as a class?
I know this is silly, but I looked through Google and forums and the problem seems to be so obvious and simple that it's hard to find a webpage or entry targeting this (or perhaps I'm asking the wrong question).
http://php.net/manual/en/language.variables.scope.php
<?php
$debug = TRUE;
function a() {
global $debug;
if($debug === TRUE) {
echo "I'm here....\n"
}
}
Better, instead of using globals you can pass it in as a parameter:
<?php
$debug = TRUE;
function a($debug = TRUE) {
if($debug === TRUE) ....
}
You can also use the $_GLOBALS array:
<?php
$debug = TRUE;
function a() {
if($_GLOBALS['debug'] === TRUE) ...
}
You can use constants, which are always in scope:
<?php
define('DEBUG', TRUE);
function a() {
if(DEBUG === TRUE) ...
}
You can also use a singleton:
function a() {
if(SingletonClass::get_instance()->debug === TRUE) {
...
}
}
You'll have to create a singleton class which extends StdClass() to get implicit ->get and ->set methods.
http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html
did you want something like this:
<?php
$debug=TRUE;
function a($debug){
if ($debug){
echo "I'm here";
}
}
a($debug);//outputs "I'm here"
?>
A few things here a(){} isn't defined as a function
function a(){
}
Next, you shouldn't try use globals unless you absolutely want them. But, you could
$debug = TRUE;
function a(){
global $debug;
if($debug)
{
echo "it is";
}
}
then call a() whenever you want to check it.
I must say I don't think this is a great practice in how you are trying to debug.
Pass variables to a function, like this:
$debug = true;
function a($debug) {
var_dump($debug);
}
a($debug);
// Outputs bool(true)

Categories