php中不知道静态函数和非静态函数的区别在哪里,这个例子也不能说明什么,请大家指教一下.
<?
class aa
{
static function temp_1()
{
echo "temp_1" . "<br>";
}
function temp_2()
{
echo "temp_2" . "<br>";
}
}
$temp=new aa();
$temp->temp_1();
$temp->temp_2();
aa::temp_1();
aa::temp_2();?>
<?
class aa
{
static function temp_1()
{
echo "temp_1" . "<br>";
}
function temp_2()
{
echo "temp_2" . "<br>";
}
}
$temp=new aa();
$temp->temp_1();
$temp->temp_2();
aa::temp_1();
aa::temp_2();?>
例如
class a{
function x() {
..........
$t = new a // $t有自己的x函數
class b{
static function f(){
......
$t = new b
$t2 = new b //共享同一個f函數,對象不會拷貝
其實和靜態屬性還不是一樣的.
<?php
class person{
public $name = 'xMan';
public $said;
public function __construct($name,$said)
{
$this->name = $name;
$this->said = $said;
}
public function getName()
{
return $this->name;
}
public function getSaid()
{
return $this->said;
}
public static $cake = 5; # cake on common desk
public static function eatCake()
{
if (self::$cake>0)
{
self::$cake--;
$_cakeLeft = self::$cake;
}else{
$_cakeLeft = 0;
}
return $_cakeLeft.' left(Co) ';
}
public $myCake = 2; # cake on my desk:)
public function eatMyCake()
{
if ($this->myCake > 0)
{
$this->myCake--;
$_cakeLeft = $this->myCake;
}else{
$_cakeLeft = 0;
}
return $this->name.': '.$_cakeLeft.' left(My) ';
}}
$homer = new person('homer','hello! I\'m homer!');
echo $homer->getName(),':',$homer->getSaid();
echo "\n1,\n";
echo $homer->eatCake();
echo "Delicious!";
echo "\n2,\n";
echo person::eatCake(); #
echo "Another one ,Not by homer -_-# ";
echo "\n3,\n";
echo $homer->eatCake(); #
echo "Oh ! Just 2 left.";
$lisa = new person('lisa','hello! I\'m lisa!');
echo $lisa->getName(),':',$lisa->getSaid();
echo "\n4,\n";
echo $lisa->eatCake(); #
echo "I get it.";
echo "\n5,\n";
echo person::eatCake();
$bart = new person('bart','hello! I\'m bart!');
echo $bart->getName(),':',$bart->getSaid();
echo "\n6,\n";
echo $bart->eatCake();
echo "Oh, Who eated the last one!!!!!";
echo "\n7,\n";
echo $bart->eatMyCake(); # haha
echo "haha~";
//echo person::eatMyCake(); # Using $this when not in object context in xxx on line 33 (if ($this->myCake > 0))
echo "\n";
echo 'bart: No,You cann\'t haha~ ';
echo "\n8,\n";
echo $lisa->eatMyCake(),'too :)';
echo "\n";
echo $homer->eatMyCake(),'too too too :)';
?>
var $test;
}
$a = new a;
$a->test = 'test_a';$b = new a;
$b->test = 'test_b';echo $a->test; //test_a
echo $b->test; //test_ba::test = 'test_a';
a::test = 'test_b';echo a::test; //test_b
abstract calss C
{
static function getAorB(arg_flag){
if(arg_flag)return new A();
else return new B();
}
}A = C::getAorB(true);类静态函数主要应用于各种模式