Global variables in class function - php

I made a irc twitch bot and i have implemented multi threading but it have caused loots of errors.
My problem is that i have functions, example:
function isMod($username){
global $mods;
if(in_array($username,$mods) !== FALSE){
return true;
}
return false;
}
But there is a problem if i call the function from a class the "global" tag seams to not work so $mods will remain null. How can i fix it?
I have tried to use
$globals['mods']
But it is not seaming to work either.
I could do it like
function isMod($username, $mods){
if(in_array($username,$mods) !== FALSE){
return true;
}
return false;
}
But i want to avoid that.

If you really want to do it with globals, try to use $GLOBALS['mods'] instead.
function isMod($username){
if(in_array($username,$GLOBALS['mods']) !== FALSE){
return true;
}
return false;
}
$GLOBALS['mods'] = array('joe');
class Test {
function foo(){
var_dump(isMod('joe'));
}
}
$test = new Test();
$test->foo();
$GLOBALS is available everywhere, just like e.g. $_GET.

Related

PHP Accessing Variable from multiple functions

Novice question but then I am a novice at this...
I have a class for registering users and I have functions for different validation. Basically, I run "mainTest" which pulls in the variables from a form and then runs each function (test1, test2). Within those functions if something doesn't validate within the function I set a variable called $error to true. What I am trying to do within the "mainTest" function check if the variable $error has been set to true in any of the other functions do something but when I echo the $error variable it just says null i.e. the functions aren't linking. (trying not to use Global Variables).
Any Ideas here is an example of how I am doing this...
class myClass {
private function test1($var1, $var2) {
if....
else {
$error = true;
return $error;
}
}
private function test2($var3, $var4) {
if....
else {
$error = true;
return $error;
}
}
public function mainTest($var1, $var2, $var3, $var4) {
$this->test1($var1, $var2);
$this->test2($var3, $var4);
if ($error == true) {
//do something
}
}
}
use an instance variable in the class ie..
class myClass {
private $error = '';
function test2()
{
//some code here
$this->error = true;
return $this->error;
}
Now you can access the error variable in other function using the $this keyword
$this->error, here's a little reading
From what you have submitted in the way of code, all of your functions return a boolean. This means that inside of your mainTest you can do something like this:
$error = test1() || test2();
This means that if either of test1 or test2 return true, error will be set to true. But if they both fail, error is false. You can use the || operator any number of times, take my trivial example for instance:
function one(){
return false;
}
function two(){
return false;
}
function three(){
return false;
}
$var = one() || two() && three();
var_dump($var);
In this example, var will be a boolean variable set to false. However, if any one of the three functions returned true, var would of corse be true.
With this, you are semantically saying "the result of one OR the result of two OR the result of three." With || true takes precedence over false, meaning that is anything is true, the end result is true.
In your example, the problem with using the class variable approach as others have suggested, is that, what if test1() sets error to true and then test2() later sets it to false. This can of corse be overcome, however it would require more logic in your mainTest function. Essentially you would need to check the value of error after each function.
Since you're returning the TRUE boolean, you can check to see each function's output to see if it's TRUE, or not:
public function mainTest($var1, $var2, $var3, $var4) {
if ($this->test1($var1, $var2) === TRUE) || $this->test2($var3, $var4) === TRUE) {
// an error occurred, because your function returned a TRUE boolean
}
}
If you'd want to re-structure your code, you can declare a public variable as part of your class and set it using your functions.
class myClass {
// ...
private $error;
private function test1($var1, $var2) {
if....
else {
$this->error = true;
}
}
// ...
public function mainTest($var1, $var2, $var3, $var4) {
$this->test1($var1, $var2);
$this->test2($var3, $var4);
if ($this->error === TRUE) {
// an error occurred
}
}
}

Call to undefined function isLoggedIn()

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

Default value if variable not sets

I sometimes have variables that might not be set and I would like to use a default parameter instead. Like here:
if ($p == "a") doSomething();
If $p is not defined PHP throws Notice: Undefined variable. To avoid this I often I used this construct in such a case:
$p = (isset($p) ? $p : "");
But that is ugly if you have to use it a lot. So I wrote a function for it:
function getIfSet(&$value, $default = '')
{
return isset($value) ? $value : $default;
}
// Example
if (getIfSet($p) == "a") doSomething();
I wonder if there is a PHP function for this or how you solve this.
Just a little improvement, prefer passing null value to $default, passing empty string can be confusing, cause correct value can be empty string.
function getIfSet(&$value, $default = null)
{
return isset($value) ? $value : $default;
}
$p = getIfSet($p);
isset() is about as clean as it gets. Although I must admit that I'm not too fond of defaulting to an empty string, simply because a variable could be an empty string, yet still "be set". I think that a default of bool false or null would be truer to the behavior of isset:
function getIfSet(&$value, $default = false)
{
return isset($value) ? $value : $default;
}
$p = getIfSet($p);
if($p !== false){
//insert or whatever
}
else{
header('Location: error.php');
exit;
}
Depending on what kind of values you're checking (maybe REQUEST data?), consider using classes. They are fun and they could be available anywhere.
Assuming you're checking POST data (if you don't, well, take this as an idea), create a class that checks this array:
class Post
{
public function __get($index)
{
if (isset($_POST[$index]))
return $_POST[$index];
else
return null;
}
}
As simple as that. You know that __get() will trigger when you try to access a non-existant property. In this case, if the property (actually, the index in the $_POST array) doesn't exist, null will be returned and no errors are generated.
Now you can do:
$params = new Post();
$foo = $params->name ?: ''; // of course this doesn't make much sense.
if (!$params->password) ...
// instead of
if (isset($_POST['password'])) ...
// you'll still have to use isset for cases like:
if (isset($_POST['user']['password']) ...
if (isset($params->user['password'])) ...
// but still looks neater I'd say
A problem you'll find soon is that $params isn't a super global variable, while $_POST are. How to solve this? Create it in the constructor of your controller class and use Dependency Injection for all other objects your are using.
I tried to make renocor's answer more clean and OOP when I came up with this solution:
class NiceArray implements ArrayAccess {
protected $array;
public function __construct(&$array) {
$this->array =& $array;
}
public function offsetExists($offset) {
return true;
}
public function offsetGet($offset) {
if (isset($this->array[$offset]))
{
return $this->array[$offset];
}
else
{
return null;
}
}
public function offsetSet($offset, $value) {
$this->array[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->array[$offset]);
}
}
Usage:
$get = new NiceArray($_GET);
if ($get['p'] == "a") doSomething();
I know the class is kind of big but this way you still have an array and you can easily use it for every array you want. You do not need to change any code you may had before. You can still access and change the data. It will even change the original array.

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)

Best way in PHP to ensure in a class that all the class functions are called only if a given condition is true

I have a class in which each function of the class have to check the exact same condition before executing its code:
class myObject
{
public function function1($argument)
{
if($condition === true)
{
//Do Something
}
}
public function function2($argument)
{
if($condition === true)
{
//Do Something
}
}
public function function3($argument)
{
if($condition === true)
{
//Do Something
}
}
public function function4($argument)
{
if($condition === true)
{
//Do Something
}
}
}
We can see that function1, function2, function3, function4 only execute their code if $condition === true.
If in the future I add another function called function5, I will have to duplicate this condition.
So my question is, what is the best way to ensure that before call ANY function in the class, a condition is true, and if the condition is false, not call the function.
My method is to use the magic function __call and make all the functions of the class private:
class myObject
{
public function __call($method,$args)
{
if($condition === true)
{
call_user_func_array(array($this,$method),$args);
}
return;
}
private function function1($argument)
{
//Do Something
}
private function function2($argument)
{
//Do Something
}
private function function3($argument)
{
//Do Something
}
private function function4($argument)
{
//Do Something
}
}
It seems to work. However, I'm unsure that it will always work and that it is a clever way of doing it.
Its pretty normal to do it your first way. But, maybe the whole design of the class is wrong? If every single one function needs the exact same condition to be true maybe you could set/check it in the constructor and treat it from there? Why recheck the condition multiple times? Can it change between function calls?
Something like that would be used this way:
try{
$myClass = new MyClass(); // if no permissions throw exception
}catch(Exception $e){
//do something
return false;
}
//we know user as permission we go on
$myClass->function1();
$myClass->function2();
The second way works but you lose some of the power of phpdoc and good editors that will autocomplete your code. This way you have to know the name of every method.

Categories