1

i would like to know. is php class variable store data for access anywhere in class without performing again.

suppose that

class myclass 
{
  public $date;

    public function __construct(){
     $this->date = date('Ymd');
    }
}

$myclass = new myclass();

$myclass->date;

so as above code if i am using $myclass->date; three time in my code. it means date() function runs three time ? or just run one time and store current date in class variable and not utilize CPU power three time in same task?

Rakesh
  • 181
  • 15
  • 1
    Using `$myclass->date` you're referencing a property value, not calling a function, so as long as you're not instantiating a new myclass instance whenever you need it, the actual date function is only being called once in the constructor – Mark Baker Apr 09 '15 at 08:55
  • 1
    The constructor is only run when you create a new object, not when you access a property of an existing object. – jeroen Apr 09 '15 at 08:56
  • Yes so it means i can access property value without calling a function ? – Rakesh Apr 09 '15 at 08:58

2 Answers2

1

as jeroen said the constructor is called only at initialisation. You can change the value of date anytime outside the class by:

$myclass->date = date('Ymd');

You may see example here: http://codepad.org/oPZlwnOS If you wish more adequate handling use getters and setters with private method state. See here more

Community
  • 1
  • 1
Miglen.com
  • 339
  • 1
  • 7
0
public function __construct(){
 $this->date = date('Ymd');
}

Will run just once, when you reference the class i.e. on:

$myclass = new myclass();

if you want to check for date each time when you call, you have to make a function:

public function currentDate(){
    return date('Ymd');
}

and then call it like:

$currentDate = $myclass->currentDate();
lrd
  • 302
  • 2
  • 12