PHP and MySQL Web Development - P36

PHP and MySQL Web Development - P36: PHP and MySQL Web Development teaches the reader to develop dynamic, secure, commercial Web sites. Using the same accessible, popular teaching style of the first edition, this best-selling book has been updated to reflect the rapidly changing landscape of MySQL and PHP. | 142 Chapter 5 Reusing Code and Writing Functions functions are slower and use more memory than iteration so you should use iteration wherever possible. In the interest of completeness we will look at a brief example shown in Listing . Listing It Is Simple to Reverse a String Using Recursion The Iterative Version Is Also Shown function reverse_r str if strlen str 0 reverse_r substr str 1 echo substr str 0 1 return function reverse_i str for i 1 i strlen str i echo substr str - i 1 return In this listing we have implemented two functions. Both of these will print a string in reverse. The function reverse_r is recursive and the function reverse_i is iterative. The reverse_r function takes a string as parameter. When you call it it will proceed to call itself each time passing the second to last characters of the string. For example if you call reverse_r Hello it will call itself a number of times with the following parameters reverse_r ello reverse_r llo reverse_r lo reverse_r o reverse_r Each call the function makes to itself makes a new copy of the function code in the server s memory but with a different parameter. It is like pretending that we are actually calling a different function each time. This stops the instances of the function from getting confused. With each call the length of the string passed in is we reach the end of the string strlen 0 the condition most recent instance of the function Next 143 reverse_r will then go on and perform the next line of code which is to echo the first character of the string it was passed in this case there is no character because the string is empty. Next this instance of the function returns control to the instance that called it namely reverse_r o . This prints the first character in its string o and returns control to the instance that called it. The process continues printing a character and then returning to the instance of the function above it in the calling order until .

Không thể tạo bản xem trước, hãy bấm tải xuống
TỪ KHÓA LIÊN QUAN
TÀI LIỆU MỚI ĐĂNG
2    62    2    29-03-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.