Prashank
Prashank

Reputation: 796

change a variable value in another function

I need some help with my php code. This is my code

class myclass extends anotherclass {

    var $bAlert;

    function myclass($var) {
        parent::anotherclass($var);
        $this->bAlert = false;
    }

function alert() {
        $this->bAlert = 'true';
        return;
    }

function display() {
        if(!$this->bAlert) {
           return;
        }
        return 'blah blah';
    }
}

Now what i want, I have a function to show something on screen when display() is called thats not the problem but i only want it to show up after alert() is called. So here is what i thought but it has a problem. I want to permanently change the value of $bAlert to true once alert() is called and of course it doesn't happen. So, anybody got any other bright ideas or any other way to do it?

Thanks

Upvotes: 0

Views: 103

Answers (2)

Ari McBrown
Ari McBrown

Reputation: 1106

Ok, I'll add my implementation for clarity

Note: For this to work, you need to use session_start(); in all the script-pages you need the user to be logged-in.

class MyClass extends AnotherClass
{
  public static
    $bAlert = false;

  // This is the magic you need!
  public function __construct()
  {
    // Check if the session-var exists, then put it into the class
    if ( array_key_exists('bAlert', $_SESSION) ) {
      self::$bAlert = $_SESSION['bAlert'];

    // Set session with the default value of the class
    } else {
      $_SESSION['bAlert'] = self::$bAlert;
    }
  }

  function setAlert($alertValue = true)
  {
    // Used type-juggle in-case of weird input
    self::$bAlert = (bool) $alertValue;

    // Not needed, but looks neat.
    return;                 
  }

  function display($message = 'Lorum ipsum')
  {
    // This part will **only** work when it's a boolean
    if ( !self::$bAlert ) {
      return;
    }

    return $message;
  }
}

Btw, if you use classes in PHP5+ try using function __construct(){} instead of function MyClassName(){}. I know it looks weird compared with other programming-languages, but in PHP5+ it just works better.

For a better understanding of Classes & Objects and Sessions, this documentation might be useful:

Upvotes: 1

Vipin Jain
Vipin Jain

Reputation: 1402

Use singleton classes

Please visit here for more info on singleton classes

EDIT:

Or you can use static variables and methods

EDIT:

See this code:

<?php 
class myclass extends anotherclass {
    static public $bAlert;
    function myclass($var) {
        parent::anotherclass($var);
        self::$bAlert = false;
    }
    static function alert() {
        self::$bAlert = 'true';
        return;
    }
    function display() {
        if(!self::$bAlert) {
        return;
        }
        return 'blah blah';
    }
}

Upvotes: 2

Related Questions