September 29th, 2013, 04:30 PM
-
Static Function : More better
I made a simple
Static Function.
can anyone tell me more?
what is static variable use actually?
what is its benefits?
teach me a good simple static function.
my code is :
PHP Code:
<?php
echo "<p>My Computer getting old each year.</p>";
function age()
{
static $age = 1;
echo "Computer age update: ". $age . "<br />"; //dot operator to used HTML tag.
$age++;
}
age();
age();
age();
?>
September 29th, 2013, 05:03 PM
-
there is a description of static in the PHP documentation and at this (near example 4).
Basically, static means the variable/function only exists once in the whole process and is "shared" across all instances.
Last edited by MrFujin; September 29th, 2013 at 05:09 PM.
September 29th, 2013, 05:32 PM
-
Originally Posted by MrFujin
Basically, static means the variable/function only exists once in the whole process and is "shared" across all instances.
friend that i know; my teacher told me it.
but i checked php.net site, too much data, php.net makes me confuse, because I am newbie,
php.net used simple class function itself.
and my teacher did not teach me class still.
it is like
I wrote here, which i learned in Static Variable in PHP post.
give me simple simple concept that i can try in wampserver.
September 29th, 2013, 05:55 PM
-
Looking at the code you have posted.
When you call age() three times, it should have this output:
Code:
Computer age update: 1
Computer age update: 2
Computer age update: 3
This is because of the static, which let it "re-use" the same variable for each call.
If you didn't specify age with static keyword, it would "re-create" the variable every time you call the function. The output - without static - would therefore be
Code:
Computer age update: 1
Computer age update: 1
Computer age update: 1
September 30th, 2013, 05:48 AM
-
Originally Posted by MrFujin
Code:
Computer age update: 1
Computer age update: 1
Computer age update: 1
great thing you told me; my teacher forgot to tell me this. lolx.
September 30th, 2013, 08:48 AM
-
echo "Computer age update: ". $age . "<br />"; //dot operator to used HTML tag.
Just curious about your comment after the code... If you are referencing the period sign needed because of the HTML, this is false. It is more a connecting item, but can be to anything.
PHP Code:
echo 'Yesterday, when ' . $firstName . $lastName . ' went to the supermarket...';
Now, the one thing that doesn't make this the best example is the fact that there will be no space between the person's first and last name, but I was just to offer a view that the . just seperates/connects multiple items within the same line.
He who knows not that he knows not is a fool, ignore him. He who knows that he knows not is ignorant, teach him. He who knows not that he knows is asleep, awaken him. He who knows that he knows is a leader, follow him.
September 30th, 2013, 10:55 AM
-