Home > php > PHP: Inner Function

PHP: Inner Function

November 9, 2010 No Comments    

PHP: Inner Function
ช่วงนี้ผมนั่งแก้ script php ที่เค้าแจกกันใน internet? แก้ไปแก้มาก็ไปเจอ function ที่อยู่ใน function ซึ่งมันก็แปลกดี ผมก็เพิ่งเคยเจอในภาษา php นี้แหละผมเลยหาข้อมูลมันก็เรียกว่า inner function หรือว่า Nested Functions จึงทำให้ผมเขียนบทความเกี่ยวกับเรื่องนี้ ซึ่งผมก็ลองทดลองแล้วก็พบว่า inner function เป็นวิธีการที่ทำงานในกรณีที่ต้องการให้ function ตัวนอกทำงานได้แน่นอนจึงอนุญาตให้ inner function สามารถทำงานได้ ซึ่งผมได้ยกตัวอย่างโค้ดไว้ดังนี้

php inner function, inner function, php เบื้องต้น, สอน php

<?
function outterA()
{
echo "outterA <br>";

function innerB($message)
{
echo "innerB <br>";
echo $message . "<br>";
}
}

outterA();
innerB("message");
?>

php inner function, inner function, php เบื้องต้น, สอน php

ซึ่งถ้าลองรันดูก็จะได้ดังรูปแต่ถ้าลองคอมเม้น ตรงที่เรียกใช้งาน outterA(); ก็จะเกิด error ขึ้นเพราะฉะนั้นถ้าจะเรียกใช้ inner function ในตัวอย่างนั้นต้องเรียกใช้งาน function ตัวนอกอย่าง outterA ก่อนที่จะเรียกใช้งาน innerB ได้ ซึ่งจากการทำงานดังกล่าวก็ทำให้เราสามารถกำหนดได้ว่าจะต้องให้ function ตัวนอกทำงานก่อนจึงจะสามารถให้ inner function สามารถทำงานได้
?

Download Source

Tags: , , ,

Comments : PHP: Inner Function

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>