Phát triển web với PHP và MySQL - p 17

Reusing Code and Writing Functions CHAPTER 5 135 FIGURE This HTML table is the result of calling create_table(). Passing a parameter allowed us to get data that was created outside the function—in this case, the array $data—into the function. As with built-in functions, user-defined functions can have multiple parameters and optional parameters. We can improve our create_table() function in many ways, but one way might be to allow the caller to specify the border or other attributes of the table. Here is an improved version of the function. It is very similar, but allows us to optionally set the table’s border width, cellspacing,. | Reusing Code and Writing Functions 135 Chapter 5 Figure This HTML table is the result of calling create_table . Passing a parameter allowed us to get data that was created outside the function in this case the array data into the function. As with built-in functions user-defined functions can have multiple parameters and optional parameters. We can improve our create_table function in many ways but one way might be to allow the caller to specify the border or other attributes of the table. Here is an improved version of the function. It is very similar but allows us to optionally set the table s border width cellspacing and cellpadding. function create_table2 data border 1 cellpadding 4 cellspacing 4 echo table border border cellpadding cellpadding . cellspacing cellspacing reset data value current data while value echo tr td value td tr n value next data echo table The first parameter for create_table2 is still required. The next three are optional because we have defined default values for them. We can create very similar output to that shown in Figure with this call to create_table2 . create_table2 my_array If we want the same data displayed in a more spread out style we could call our new function as follows create_table2 my_array 3 8 8 5 Reusing Code and Writing Functions 136 Using PHP Part I Optional values do not all need to be provided we can provide some and ignore some. Parameters will be assigned from left to right. Keep in mind that you cannot leave out one optional parameter but include a later listed one. In this example if you want to pass a value for cellspacing you will have to pass one for cellpadding as well. This is a common cause of programming errors. It is also the reason that optional parameters are specified last in any list of parameters. The following function call create_table2 my_array 3 is perfectly legal and will result in border being set to 3 and cellpadding and cellspacing being set to their defaults. Scope You might have .

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
Đã 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.