Heim >Backend-Entwicklung >PHP-Tutorial >PHP学习日记(1)——类、函数的使用
PHP学习日记(一)——类、函数的使用
一、自定义函数
<span style="color: #0000ff;">function</span> add(<span style="color: #800080;">$a</span>,<span style="color: #800080;">$b</span><span style="color: #000000;">){ </span><span style="color: #800080;">$c</span>=<span style="color: #800080;">$a</span>+<span style="color: #800080;">$b</span><span style="color: #000000;">; </span><span style="color: #0000ff;">echo</span> 'add test:'<span style="color: #000000;">; </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$c</span><span style="color: #000000;">; </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$c</span><span style="color: #000000;">;}add(</span>1,2);
输出结果:
add test:3
二、调用类里面函数
1、双冒号::,不用实例化,直接类名调用
<span style="color: #0000ff;">class</span><span style="color: #000000;"> test{ </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> add(<span style="color: #800080;">$a</span>,<span style="color: #800080;">$b</span><span style="color: #000000;">){ </span><span style="color: #800080;">$c</span>=<span style="color: #800080;">$a</span>+<span style="color: #800080;">$b</span><span style="color: #000000;">; </span><span style="color: #0000ff;">echo</span> 'class test:'<span style="color: #000000;">; </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$c</span><span style="color: #000000;">; </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$c</span><span style="color: #000000;">; }}test</span>::add(1,2);
2、->,实例化后的对象使用
<span style="color: #0000ff;">class</span><span style="color: #000000;"> test{ </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> add(<span style="color: #800080;">$a</span>,<span style="color: #800080;">$b</span><span style="color: #000000;">){ </span><span style="color: #800080;">$c</span>=<span style="color: #800080;">$a</span>+<span style="color: #800080;">$b</span><span style="color: #000000;">; </span><span style="color: #0000ff;">echo</span> 'class test:'<span style="color: #000000;">; </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$c</span><span style="color: #000000;">; </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$c</span><span style="color: #000000;">; }}</span><span style="color: #800080;">$object</span>=<span style="color: #0000ff;">new</span><span style="color: #000000;"> test();</span><span style="color: #800080;">$object</span>->add(1,3);