Working with Functions and Classes

Size: px
Start display at page:

Download "Working with Functions and Classes"

Transcription

1 CHAPTER 5 Working with Functions and Classes IN THIS CHAPTER: 5.1 Defining Custom Functions 5.2 Avoiding Function Duplication 5.3 Accessing External Variables from Within a Function 5.4 Setting Default Values for Function Arguments 5.5 Processing Variable-Length Argument Lists 5.6 Returning Multiple Values from a Function 5.7 Manipulating Function Inputs and Outputs by Reference 5.8 Dynamically Generating Function Invocations 5.9 Dynamically Defining Functions 5.10 Creating Recursive Functions 5.11 Defining Custom Classes 5.12 Automatically Executing Class Initialization and Deinitialization Commands 5.13 Deriving New Classes from Existing Ones 5.14 Checking If Classes and Methods Have Been Defined 5.15 Retrieving Information on Class Members 5.16 Printing Instance Properties 5.17 Checking Class Antecedents 5.18 Loading Class Definitions on Demand 5.19 Comparing Objects for Similarity 5.20 Copying Object Instances 5.21 Creating Statically-Accessible Class Members 5.22 Altering Visibility of Class Members 5.23 Restricting Class Extensibility 5.24 Overloading Class Methods 5.25 Creating Catch-All Class Methods 5.26 Auto-Generating Class API Documentation 131

2 132 PHP Programming s As with any programming language worth its salt, PHP supports functions and classes, which you can use to make your code more modular, maintainable, and reusable. Functions, in particular, have been wellsupported in PHP for a long time, and so most of the new developments in PHP have focused on the object model, which has been completely redesigned to bring PHP in closer compliance with OOP standards. The solutions in this chapter are therefore a mix of old and new techniques. Among the golden oldies: dealing with variable scope; using variable-length argument lists and default arguments; extending classes; using class constructors; and checking class ancestry. Among the brash newcomers: overloading methods; cloning and comparing objects; using abstract classes; and protecting class members from outside access. Together, they add up to a fairly interesting collection. See for yourself! 5.1 Defining Custom Functions You want to define your own functions. Use PHP s function keyword to name and define custom functions, and invoke them as required: // define function // to calculate circle area function getcirclearea($radius) { return pi() * $radius * $radius; // invoke function // for circle of radius 10 // result: "The area of a circle with radius 10 is " echo "The area of a circle with radius 10 is ". getcirclearea(10);

3 Chapter 5: Working with Functions and Classes 133 A function is an independent block of code that performs a specific task, and can be use more than once at different points within the main program. Every programming language comes with built-in functions and typically also allows developers to define their own custom functions. PHP is no exception to this rule. Function definitions in PHP begin with the function keyword, followed by the function name (this can be any string that conforms to PHP s naming rules), a list of arguments in parentheses, and the function s code within curly braces. Function arguments make it possible to supply variable input to the function at run time. Within the function itself, the return keyword is used to return the result of the function s operations to the calling program. In the previous example the function is named getcirclearea(), accepts a single argument (the circle radius, represented by $radius), and uses this argument to calculate the area of the circle. Once a named function has been defined in the manner described previously, using it is as simple as calling (or invoking) it by its name, in much the same way one would call built-in functions such as implode() or exists(). An example of such function invocation can be seen in the previous listing, which demonstrates the newly-minted getcirclearea() function being invoked with an argument of 10 units (the circle radius) and returning a value of units (the corresponding circle area). 5.2 Avoiding Function Duplication You want to test if a function has already been defined. Use PHP s function_exists() function: // sample function function dothis() { return false;

4 134 PHP Programming s // test if function exists // result: "Function exists" echo function_exists("dothis")? "Function exists" : "Function does not exist"; // result: "Function does not exist" echo function_exists("dothat")? "Function exists" : "Function does not exist"; It s a good idea to check for the prior existence of a function before declaring it, because PHP generates an error on any attempt to re-declare a previously defined function. The function_exists() function provides an easy solution to the problem, as illustrated in the previous example. 5.3 Accessing External Variables from Within a Function You want to access a variable from the main program within a function definition. Use the global keyword within the function definition to import the variable from the global scope: // define variable outside function $name = "Susan"; // access variable from within function function whoami() { global $name; return $name;

5 Chapter 5: Working with Functions and Classes 135 // call function // result: "Susan" echo whoami(); By default, variables within a function are isolated from variables outside it in PHP. The values assigned to them, and the changes made to them, are thus local and restricted to the function space alone. Often, however, there arises a need to share a variable from the main program with the code inside a function definition. You can accomplish this by making the variable global, so that it can be manipulated both inside and outside the function. PHP s global keyword, when prefixed to a variable name within a function definition, takes care of making the variable global. This is illustrated in the previous listing. An alternative way of accomplishing the same thing is to access the variable by name from the special $_GLOBALS associative array, as demonstrated in the next listing: // define variable outside function $name = "Susan"; // access variable from within function function whoami() { return $GLOBALS['name']; // call function // result: "Susan" echo whoami(); For a more detailed demonstration of variable scope inside and outside a function, consider the following listing: // define a variable outside the function $name = "Joe";

6 136 PHP Programming s // define a function to alter the variable function whoami() { // access the variable from inside the function global $name; // check the variable // result: "I am Joe at the beginning of the function." echo "I am $name at the beginning of the function.\n"; // redefine the variable inside the function $name = "Jane"; // check the variable // result: "I am Jane at the end of the function." echo "I am $name at the end of the function.\n"; // check the variable // result: "I am Joe before running the function." print "I am $name before running the function.\n"; // call the function echo whoami(); // check the variable // result: "I am Jane after running the function." print "I am $name after running the function.\n"; NOTE PHP also comes with so-called superglobal variables (or superglobals) variables that are always available, regardless of whether you re inside a function or outside it. The $_SERVER, $_ POST, and $_GET variables are examples of superglobals, which is why you can access things like the currently executing script s name or form values even inside a function. The good news about superglobals is that they re always there when you need them, and you don t need to jump through any hoops to use the data stored inside them. The bad news is that the superglobal club is a very exclusive one, and you can t turn any of your own variables into superglobals. Read more about superglobals and variable scope at and

7 Chapter 5: Working with Functions and Classes Setting Default Values for Function Arguments You want to set default values for one or more function arguments, thereby making them optional. Assign default values to those arguments in the function signature: // define function // with default arguments function orderpizza($crust, $toppings, $size="12") { return "You asked for a $size-inch pizza with a $crust crust and these toppings: ". implode(', ', $toppings); // call function without optional third argument // result: "You asked for a 12-inch pizza with a // thin crust and these toppings: cheese, anchovies" echo orderpizza("thin", array("cheese", "anchovies")); Normally, PHP expects the number of arguments in a function invocation to match that in the corresponding function definition, and it will generate an error in case of a smaller argument list. However, you might want to make some arguments optional, using default values if no data is provided by the user. You can do this by assigning values to the appropriate arguments in the function definition. TIP Place optional arguments after mandatory arguments in the function s argument list.

8 138 PHP Programming s 5.5 Processing Variable-Length Argument Lists You want your function to support a variable number of arguments. Use PHP s func_get_args() function to read a variable-length argument list: // define a function function somefunc() { // get the number of arguments passed $numargs = func_num_args(); // get the arguments $args = func_get_args(); // print the arguments print "You sent me the following arguments: "; for ($x=0; $x<sizeof($args); $x++) { print "\nargument $x: "; // check if an array was passed // iterate and print contents if so if (is_array($args[$x])) { print " ARRAY "; foreach ($args[$x] as $index=>$element) { print " $index => $element "; else { print " $args[$x] "; // call the function with different arguments // returns: "You sent me the following arguments: // Argument 0: red // Argument 1: green // Argument 2: blue

9 Chapter 5: Working with Functions and Classes 139 // Argument 3: ARRAY 0 => 4 1 => 5 // Argument 4: yellow" somefunc("red", "green", "blue", array(4,5), "yellow"); PHP s func_get_args() function is designed specifically for functions that receive argument lists of varying length. When used inside a function definition, func_get_args() returns an array of all the arguments passed to the function; the individual arguments can then be extracted and processed with a for() loop. Remember that the argument list can contain a mixture of scalar variables and arrays, so if you re unsure what input to expect, make it a point to check the type of each argument before deciding how to process it. Here s another example of this in action: // define function that accepts // a dynamic number of arguments function calcsum() { $sum = 0; // get argument list as array $args = func_get_args(); // process argument list // add each argument to previous total // if any of the arguments is an array // use a loop to process it for ($x=0; $x<sizeof($args); $x++) { if (is_array($args[$x])) { foreach ($args[$x] as $a) { $sum += $a; else { $sum += $args[$x]; return $sum;

10 140 PHP Programming s // call function with 2 scalar arguments // result: "The sum of 1 and 10 is 11." echo "The sum of 1 and 10 is ". calcsum(1,10). ".\n"; // call function with mixture // of 3 scalar and array arguments // result: " The sum of 1, 2, 5 and 1 is 9." echo "The sum of 1, 2, 5 and 1 is ". calcsum(1, 2, array(5,1)). ".\n"; 5.6 Returning Multiple Values from a Function You want to return more than one value from a function. Place the set of desired return values in an array, and return that instead: // define function // that returns more than one value function getuserinfo() { return array("simon Doe", "London", "simon@some.domain.edu"); // extract returned list into separate variables // result: "My name is Simon Doe from London. // Get in touch at simon@some.domain.edu" list ($name, $place, $ ) = getuserinfo(); echo "My name is $name from $place. Get in touch at $ "; A PHP function can only return a single value to the caller; however, this value may be of any supported type (scalar, array, object, and so on). So, if you d like a function to return multiple values, the simplest way to do this is to add them all to an array and return that instead.

11 Chapter 5: Working with Functions and Classes Manipulating Function Inputs and Outputs by Reference You want to pass input arguments to, or receive return values from, a function by reference (instead of by value). To pass an argument by reference, prefix the argument with the & symbol in the function definition: // define a function // that changes a variable by reference function changeday(&$day) { $day = "Thursday"; return $day; // define a variable outside the function $day = "Sunday"; // check variable // result: "Before running changeday(), it is Sunday." echo "Before running changeday(), it is $day.\n"; // pass variable by reference changeday($day); // check variable // result: "After running changeday(), it is Thursday." echo "After running changeday(), it is $day.";

12 142 PHP Programming s To return a value by reference, prefix both the function name and the function invocation with the & symbol: // define a function // that returns a value by reference function &incrementnum() { global $num; $num++; return $num; // define a variable outside the function $num = 0; // invoke function // get return value of function as reference // result: "Number is 1." $retval =& incrementnum(); echo "Number is $retval.\n"; // invoke function again incrementnum(); // check reference // result: "Number is 2." echo "Number is $retval.\n"; By default, arguments to PHP functions are passed by value that is, a copy of the variable is passed to the function, with the original variable remaining untouched. However, PHP also allows you to pass by reference that is, instead of passing a value to a function, you pass a reference to the original variable and have the function act on that instead of a copy. In the first example, because the argument to changeday() is passed by reference, the change occurs in the original variable rather than in a copy. That s the reason why, when you re-access the variable $day after running the function on it, it returns the modified value Thursday instead of the original value Sunday. It s also possible to get a reference to a function s return value, as in the second example. There, $retval is a reference to (not a copy of) a global variable.

13 Chapter 5: Working with Functions and Classes 143 So, every time the global variable changes, the value of $retval changes as well. If, instead, you set things up to get a copy of (not a reference to) the function s return value, the value of $retval would remain 1. NOTE References make it possible to manipulate variables outside the scope of a function, in much the same way as the global keyword did in the listing in 5.3: Accessing External Variables From Within a Function. The PHP manual makes the relationship clear when it says when you declare [a] variable as global $var, you are in fact creating reference to a global variable. Read more about references at Dynamically Generating Function Invocations You want to dynamically generate a function invocation from a PHP variable. Use parentheses to interpolate the variable name with the function invocation: // sample function function playtrack($id) { echo "Playing track $id"; // define variable for operation $op = "play"; // build function name from variable $func = $op. "Track"; // call function // result: "Playing track 45" $func(45);

14 144 PHP Programming s PHP supports the use of variable functions, wherein a function name is dynamically generated by combining one or more variables. When PHP encounters such a variable function, it first evaluates the variable(s) and then looks for a function matching the result of the evaluation. The previous listing illustrates this, creating a function invocation from a variable. 5.9 Dynamically Defining Functions You want to define a function dynamically when another function is invoked. Nest one function inside the other: // define function function findoil() { // define nested function // this function only becomes available // once the outer function has been invoked function startdrilling() { echo "Started drilling. We're gonna be rich!\n"; echo "Found an oil well. Thar she blows!\n"; // run functions // returns: "Found an oil well. Thar she blows!" findoil(); // returns: "Started drilling. We're gonna be rich!" startdrilling(); PHP supports nested functions, wherein the inner function is defined only when the outer one is invoked. In the previous listing, the startdrilling() function

15 Chapter 5: Working with Functions and Classes 145 does not exist until after the findoil() function is called. You can verify this by invoking startdrilling() before and after invoking findoil(); PHP will return an undefined function fatal error in the first instance, but not in the second Creating Recursive Functions You want to recursively perform a task. Write a recursive function that runs repeatedly until a particular condition is met: // recursive function // to calculate factorial function calcfactorial($num) { // define variable to hold product static $product = 1; // recurse until $num becomes 1 if ($num > 1) { $product = $product * $num; $num--; calcfactorial($num); return $product; // result: "Factorial of 5 is 120" echo "Factorial of 5 is ". calcfactorial(5); PHP supports recursive functions, which are essentially functions that call themselves repeatedly until a particular condition is met. Recursive functions are commonly used to process nested data collections for example, multidimensional arrays, nested file collections, XML trees, and so on. The previous listing illustrates

16 146 PHP Programming s a simple example of recursion a function that calculates the factorial of a number by repeatedly calling itself with the number, reducing it by 1 on each invocation. Recursion stops only once the number becomes equal to 1. Here s another example of recursion; this one processes a directory collection and prints a list of the files found: // define recursive function // to display directory contents function recursedir($dir) { // check for valid argument if (!is_dir($dir)) { die("argument '$dir' is not a directory!"); // open directory handle $dh = opendir($dir) or die ("Cannot open directory '$dir'!"); // iterate over files while (($file = readdir($dh))!== false) { // ignore. and.. items if ($file!= "." && $file!= "..") { if (is_dir("$dir/$file")) { // if this is a subdirectory // recursively process it recursedir("$dir/$file"); else { // if this is a file // print file name and path echo "$dir/$file \n"; // recursively process directory recursedir('/tmp'); Here, every time the function encounters a directory entry, it first checks to see if that value is a file or a directory. If it s a directory, the function calls itself again to process the directory; if it s a file, the file name is printed. The process continues until the end of the directory tree is reached.

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Control

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

What is PHP? [1] Figure 1 [1]

What is PHP? [1] Figure 1 [1] PHP What is PHP? [1] PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP is free to download and use Figure

More information

Chapter 2: Functions and Control Structures

Chapter 2: Functions and Control Structures Chapter 2: Functions and Control Structures TRUE/FALSE 1. A function definition contains the lines of code that make up a function. T PTS: 1 REF: 75 2. Functions are placed within parentheses that follow

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2013 C++ Programming Language Lab # 6 Functions C++ Programming Language Lab # 6 Functions Objective: To be familiar with

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Lecture 5: Methods CS2301

Lecture 5: Methods CS2301 Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration IT441 Network Services Administration Subroutines DRAFT (a.k.a., Functions, Methods, etc.) Organizing Code We have recently discussed the topic of organizing data (i.e., arrays and hashes) in order to

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

More information

PHP Syntax. PHP is a great example of a commonly-used modern programming language.

PHP Syntax. PHP is a great example of a commonly-used modern programming language. PHP is a great example of a commonly-used modern programming language. C was first released in 1972, PHP in 1995. PHP is an excellent language choice for software that requires an easy way to do things

More information

Lab 9: Creating a Reusable Class

Lab 9: Creating a Reusable Class Lab 9: Creating a Reusable Class Objective This will introduce the student to creating custom, reusable classes This will introduce the student to using the custom, reusable class This will reinforce programming

More information

PHP Foundations. Rafael Corral, Lead Developer 'corephp' CMS Expo 2011

PHP Foundations. Rafael Corral, Lead Developer 'corephp' CMS Expo 2011 PHP Foundations Rafael Corral, Lead Developer 'corephp' CMS Expo 2011 What is New Object model Assignments and Object Copying Constructors Standard PHP Library (SPL) New Functions / Extensions Much More...

More information

Allegro CL Certification Program

Allegro CL Certification Program Allegro CL Certification Program Lisp Programming Series Level I Review David Margolies 1 Summary 1 A lisp session contains a large number of objects which is typically increased by user-created lisp objects

More information

WINTER. Web Development. Template. PHP Variables and Constants. Lecture

WINTER. Web Development. Template. PHP Variables and Constants. Lecture WINTER Template Web Development PHP Variables and Constants Lecture-3 Lecture Content What is Variable? Naming Convention & Scope PHP $ and $$ Variables PHP Constants Constant Definition Magic Constants

More information

We d like to hear your suggestions for improving our indexes. Send to

We d like to hear your suggestions for improving our indexes. Send  to Index [ ] (brackets) wildcard, 12 { } (curly braces) in variables, 41 ( ) (parentheses) in variables, 41 += (append) operator, 45 * (asterisk) wildcard, 12 $% automatic variable, 16 $+ automatic variable,

More information

CERTIFICATE IN WEB PROGRAMMING

CERTIFICATE IN WEB PROGRAMMING COURSE DURATION: 6 MONTHS CONTENTS : CERTIFICATE IN WEB PROGRAMMING 1. PROGRAMMING IN C and C++ Language 2. HTML/CSS and JavaScript 3. PHP and MySQL 4. Project on Development of Web Application 1. PROGRAMMING

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

CLIL-6-PHP-6. Arrays - part 1. So far we've looked at the basic variables types such as strings and integers, as

CLIL-6-PHP-6. Arrays - part 1. So far we've looked at the basic variables types such as strings and integers, as Arrays - part 1 Introduction So far we've looked at the basic variables types such as strings and integers, as well as a variety of functions you can use to manipulate these data types. Beyond the basic

More information

Methods. CSE 114, Computer Science 1 Stony Brook University

Methods. CSE 114, Computer Science 1 Stony Brook University Methods CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Opening Problem Find multiple sums of integers: - from 1 to 10, - from 20 to 30, - from 35 to 45,... 2

More information

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Announcements PS 3 is due Thursday, 10/6 Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am Room TBD Scope: Lecture 1 to Lecture 9 (Chapters 1 to 6 of text) You may bring a sheet of paper (A4, both sides) Tutoring

More information

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users

Let's Look Back. We talked about how to create a form in HTML. Forms are one way to interact with users Introduction to PHP Let's Look Back We talked about how to create a form in HTML Forms are one way to interact with users Users can enter information into forms which can be used by you (programmer) We

More information

Object Oriented Programming in C#

Object Oriented Programming in C# Introduction to Object Oriented Programming in C# Class and Object 1 You will be able to: Objectives 1. Write a simple class definition in C#. 2. Control access to the methods and data in a class. 3. Create

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

1/22/2017. Chapter 2. Functions and Control Structures. Calling Functions. Objectives. Defining Functions (continued) Defining Functions

1/22/2017. Chapter 2. Functions and Control Structures. Calling Functions. Objectives. Defining Functions (continued) Defining Functions Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition Objectives In this chapter, you will: Study how to use functions to organize your PHP code Learn about variable scope

More information

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos. Lecture 05: Methods AITI Nigeria Summer 2012 University of Lagos. Agenda What a method is Why we use methods How to declare a method The four parts of a method How to use (invoke) a method The purpose

More information

CS1150 Principles of Computer Science Methods

CS1150 Principles of Computer Science Methods CS1150 Principles of Computer Science Methods Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Opening Problem Find the sum of integers from 1 to

More information

B. V. Patel Institute of BMC & IT 2014

B. V. Patel Institute of BMC & IT 2014 Unit 1: Introduction Short Questions: 1. What are the rules for writing PHP code block? 2. Explain comments in your program. What is the purpose of comments in your program. 3. How to declare and use constants

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II CS313D: ADVANCED PROGRAMMING LANGUAGE Lecture 3: C# language basics II Lecture Contents 2 C# basics Methods Arrays Methods 3 A method: groups a sequence of statement takes input, performs actions, and

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

LESSON 6 FLOW OF CONTROL

LESSON 6 FLOW OF CONTROL LESSON 6 FLOW OF CONTROL This lesson discusses a variety of flow of control constructs. The break and continue statements are used to interrupt ordinary iterative flow of control in loops. In addition,

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Alternatively, use : after else and use a final endif. Blocks of statements are grouped by { } Sys.Prog & Scripting - HW Univ 2

Alternatively, use : after else and use a final endif. Blocks of statements are grouped by { } Sys.Prog & Scripting - HW Univ 2 Systems Programming & Scripting Lecture 18: Control Structures Sys.Prog & Scripting - HW Univ 1 Example: If

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and

More information

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות 2 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static,

More information

Control Structures. Important Semantic Difference

Control Structures. Important Semantic Difference Control Structures Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block only has one statement, you must include the braces.

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

More information

PHP Functions and Arrays. Orlando PHP Meetup Zend Certification Training March 2009

PHP Functions and Arrays. Orlando PHP Meetup Zend Certification Training March 2009 PHP Functions and Arrays Orlando PHP Meetup Zend Certification Training March 2009 Functions Minimal syntax function name() { } PHP function names are not case-sensitive. All functions in PHP return a

More information

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Software Development. Modular Design and Algorithm Analysis

Software Development. Modular Design and Algorithm Analysis Software Development Modular Design and Algorithm Analysis Precondition and Postcondition To create a good algorithm, a programmer must be able to analyse a precondition (starting state) and a postcondition

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17 CS313D: ADVANCED PROGRAMMING LANGUAGE Lecture 3: C# language basics II Lecture Contents 2 C# basics Methods Arrays 1 Methods : Method Declaration: Header 3 A method declaration begins with a method header

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions. 6 Functions TOPICS 6.1 Focus on Software Engineering: Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5 Passing Data by Value 6.6 Focus

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables

More information

Exceptions, Case Study-Exception handling in C++.

Exceptions, Case Study-Exception handling in C++. PART III: Structuring of Computations- Structuring the computation, Expressions and statements, Conditional execution and iteration, Routines, Style issues: side effects and aliasing, Exceptions, Case

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון 22 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static, compile time representation of object-oriented

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y ); - 50 - Control Structures: 8. Functions (II) Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

More information

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved. C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today: Java expressions and operators concluded Java Statements: Conditionals: if/then, if/then/else Loops: while, for Next

More information

8. Control statements

8. Control statements 8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CIW 1D CIW JavaScript Specialist.

CIW 1D CIW JavaScript Specialist. CIW 1D0-635 CIW JavaScript Specialist http://killexams.com/exam-detail/1d0-635 Answer: A QUESTION: 51 Jane has created a file with commonly used JavaScript functions and saved it as "allfunctions.js" in

More information

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object CS1046 Lab 5 Timing: This lab should take you approximately 2 hours. Objectives: By the end of this lab you should be able to: Recognize a Boolean variable and identify the two values it can take Calculate

More information

Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects CS256 Computer Science I Kevin Sahr, PhD Lecture 11: Objects 1 Programs as Models remember: we write programs to solve realworld problems programs act as models of the real-world problem to be solved one

More information

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.5: Methods A Deeper Look Xianrong (Shawn) Zheng Spring 2017 1 Outline static Methods, static Variables, and Class Math Methods with Multiple

More information

Iterative Languages. Scoping

Iterative Languages. Scoping Iterative Languages Scoping Sample Languages C: static-scoping Perl: static and dynamic-scoping (use to be only dynamic scoping) Both gcc (to run C programs), and perl (to run Perl programs) are installed

More information

FUNCTIONS. The Anatomy of a Function Definition. In its most basic form, a function definition looks like this: function square(x) { return x * x; }

FUNCTIONS. The Anatomy of a Function Definition. In its most basic form, a function definition looks like this: function square(x) { return x * x; } 2 FUNCTIONS We have already used several functions in the previous chapter things such as alert and print to order the machine to perform a specific operation. In this chapter, we will start creating our

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

JavaScript Basics. The Big Picture

JavaScript Basics. The Big Picture JavaScript Basics At this point, you should have reached a certain comfort level with typing and running JavaScript code assuming, of course, that someone has already written it for you This handout aims

More information

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script.

LESSON 3. In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script. LESSON 3 Flow Control In this lesson you will learn about the conditional and looping constructs that allow you to control the flow of a PHP script. In this chapter we ll look at two types of flow control:

More information

Anatomy of a Class Encapsulation Anatomy of a Method

Anatomy of a Class Encapsulation Anatomy of a Method Writing Classes Writing Classes We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on: class definitions instance data encapsulation and

More information

IC Language Specification

IC Language Specification CS 301 Spring 2016 IC Language Specification The IC Language For the implementation project, you will build a compiler for an object-oriented language called IC (for Irish Coffee 1 ), which is essentially

More information

Visual Analyzer V2.1 User s Guide

Visual Analyzer V2.1 User s Guide Visual Analyzer V2.1 User s Guide Visual Analyzer V2.1 User s Guide Page 2 Preface Purpose of This Manual This manual explains how to use the Visual Analyzer. The Visual Analyzer operates under the following

More information

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods Encapsulation You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the program

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

UNIT 3

UNIT 3 UNIT 3 Presentation Outline Sequence control with expressions Conditional Statements, Loops Exception Handling Subprogram definition and activation Simple and Recursive Subprogram Subprogram Environment

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

Web Application Development

Web Application Development Web Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie JavaScript JAVASCRIPT FUNDAMENTALS Agenda

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

Introduction to PHP. Handling Html Form With Php. Decisions and loop. Function. String. Array

Introduction to PHP. Handling Html Form With Php. Decisions and loop. Function. String. Array Introduction to PHP Evaluation of Php Basic Syntax Defining variable and constant Php Data type Operator and Expression Handling Html Form With Php Capturing Form Data Dealing with Multi-value filed Generating

More information

COMP6700/2140 Methods

COMP6700/2140 Methods COMP6700/2140 Methods Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 9 March 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Methods 9 March 2017 1 / 19 Methods

More information