Sololearn PHP Course
Sololearn PHP Course
Sololearn PHP Course
Welcome to PHP
PHP: Hypertext Preprocessor (PHP) is a free, highly popular, open source scripting language. PHP
scripts are executed on the server.
Before starting this tutorial, you should have a basic understanding of HTML.
PHP has enough power to work at the core of WordPress , the busiest blogging system on the
web. It also has the degree of depth required to run Facebook , the web's largest social network!
PHP is a...
Website
Home page
Markup language
Server side programming language
Why PHP
PHP runs on numerous, varying platforms, including Windows, Linux, Unix, Mac OS X, and so on.
PHP is compatible with almost any modern server, such as Apache, IIS, and more.
PHP supports a wide range of databases.
PHP is free!
PHP is easy to learn and runs efficiently on the server side.
Can you run PHP on Linux?
No
Yes
PHP Syntax
<?php
// PHP code goes here
?>
Here is an example of a simple PHP file. The PHP script uses a built in function called "echo" to
output the text "Hello World!" to a web page.
<html>
<head>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
<html>
<head>
</head>
<body>
<script language="php">
echo "Hello World!";
</script>
</body>
</html>
However, the latest version of PHP removes support for <script language="php"> tags. As such,
Which of the following is correct when using PHP with the script tag?
<script type="text/javascript">
<script language="php">
<script type="application/ecmascript">
You can also use the shorthand PHP tags, <? ?>, as long as they're supported by the server.
<?
echo "Hello World!";
?>
However, <?php ?>, as the official standard, is the recommended way of defining PHP scripts.
<?php
<?
<php
Echo
<?php
?>
PHP Statements
<?php
echo "A";
echo "B";
echo "C";
?>
?>
Result:
Comments
In PHP code, a comment is a line that is not executed as part of the program. You can use
comments to communicate to others so they understand what you're doing, or as a reminder to
yourself of what you did.
<?php
?>
Result:
Multi-Line Comments
Multi-line comments are used for composing comments that take more than a single line.
A multi-line comment begins with /* and ends with */.
<?php
?>
Adding comments as you write your code is a good practice. It helps others understand your
thinking and makes it easier for you to recall your thought processes when you refer to your code
later on.
For example:
<?php
$name = 'John';
$age = 25;
echo $name;
// Outputs 'John'
?>
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
Unlike other programming languages, PHP has no command for declaring a variable. It is created
Constants are similar to variables except that they cannot be changed or undefined after they've
been defined.
Begin the name of your constant with a letter or an underscore.
To create a constant, use the define() function:define (name, value, case-insensitive)
Parameters:
name: Specifies the name of the constant;
value: Specifies the value of the constant;
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false;
<?php
echo MSG;
?>
<?php
echo msg;
?>
Data Types
PHP String
A string is a sequence of characters, like "Hello world!"
A string can be any text within a set of single or double quotes. <?php
?>
You can join two strings together using the dot ( .) concatenation operator.
PHP Integer
An integer is a whole number (without decimals) that must fit the following criteria:
- It cannot contain commas or blanks
- It must not have a decimal point
- It can be either positive or negative <?php
?>
PHP Float
PHP Boolean
<?php
$str = "10";
$int = 20;
echo ($sum);
// Outputs 30
?>
PHP automatically converts each variable to the correct data type, according to its value. This is
why the variable $str is treated as a number in the addition.
Variables Scope
<?php
$name = 'David';
function getName() {
echo $name;
getName();
This script will produce an error, as the $name variable has a global scope, and is not accessible
within the getName() function. Tap continue to see how functions can access global variables.
Functions will be discussed in the coming lessons.
A syntax error
The PHP tag was not opened
The variable was not defined within the function
<?php
$name = 'David';
function getName() {
global $name;
echo $name;
getName();
//Outputs 'David'
?>
==> 89
Variable Variables
With PHP, you can use one variable to specify another variable's name.
So, a variable variable treats the value of another variable as its name.
For example:
<?php
$a = 'hello';
$hello = "Hi!";
echo $$a ;
?>
$$a is a variable that is using the value of another variable, $a, as its name. The value of $a is
equal to "hello". The resulting variable is $hello, which holds the value "Hi!".
What output results from the following code?
$x = 'y';
$y = 'x';
echo $$x;
Output: x
Operators
Arithmetic Operators
Arithmetic operators work with numeric values to perform common arithmetical operations.
Example:
<?php
$num1 = 8;
$num2 = 6;
//Addition
//Subtraction
//Multiplication
//Division
?>
Modulus
The modulus operator, represented by the % sign, returns the remainder of the division of the first
operand by the second operand:
<?php
$x = 14;
$y = 3;
echo $x % $y ; // 2
?>
If you use floating point numbers with the modulus operator, they will be converted
to integers before the operation.
Increment & Decrement
$x+1;
Increment and decrement operators either precede or follow a variable. $x++; // post-increment
$x--; // post-decrement
++$x; // pre-increment
--$x; // pre-decrement
The difference is that the post-increment returns the original value before it changes the variable,
while the pre-increment changes the variable first and then returns the value.
Example: $a = 2; $b = $a++; // $a=3, $b=2
Assignment Operators
$num2 = $num1;
$num1 and $num2 now contain the value of 5.
Example:
<?php
$x = 50;
$x += 100;
echo $x;
// Outputs: 150
?>
Comparison Operators
The PHP comparison operators are used to compare two values (number or string ).
Logical Operators
What is the return value of the following expression, if $num1 = 5 and $num2
= 3?
($num1 >1 && $num2 < $num1)
TRUE
FALSE
Arrays
An array is a special variable, which can hold more than one value
at a time.
If you have a list of items (a list of names, for example), storing
them in single variables would look like this: $name1 = "David";
$name2 = "Amy";
$name3 = "John";
But what if you have 100 names on your list? The solution: Create
an array!
Numeric Arrays
Remember that the first element in an array has the index of 0, not 1.
Numeric Arrays
You can have integers, strings, and other data types together in one array.
Example:
<?php
$myArray[0] = "John";
$myArray[1] = "<strong>PHP</strong>";
$myArray[2] = 21;
?>
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array: $people = array ("David"=>"27", "Amy"=>"21",
"John"=>"42");
// or
$people['David'] = "27";
$people['Amy'] = "21";
$people['John'] = "42";
In the first example, note the use of the => signs in assigning values to the named keys.
'key', value
key = value
'key' => value
key != value
Multi-Dimensional Arrays
The dimension of an array indicates the number of indices you would need to select an element.
- For a two-dimensional array, you need two indices to select an element
- For a three-dimensional array, you need three indices to select an element
Arrays more than three levels deep are difficult to manage.
);
Now the two-dimensional $people array contains 3 arrays, and it has two indices: row and column.
To access the elements of the $people array, we must point to the two indices.
False
True
Conditional Statements
} else {
You can also use the if statement without the else statement, if you do not need to do
If Else
The example below will output the greatest number of the two.
<?php
$x = 10;
$y = 20;
if ( $x >= $y ) {
echo $x;
} else {
echo $y;
}
// Outputs "20"
?>
Syntax:if (condition) {
} elseif (condition) {
} else {
You can add as many elseif statements as you want. Just note, that the elseif statement must
For example:
<?php
$age = 21;
if ($age<=13) {
echo "Child.";
} else {
echo "Adult";
//Outputs "Adult"
?>
We used the logical AND (&&) operator to combine the two conditions and check to determine
whether $age is between 13 and 19.
The curly braces can be omitted if there only one statement after the if/elseif/else.
For example:
if($age<=13)
echo "Child";
else
echo "Adult";
Loops
When writing code, you may want the same block of code to run over and over again. Instead of
adding several almost equal code-lines in a script, we can use loops to perform a task like this.
code to be executed;
If the condition never becomes false , the statement will continue to execute indefinitely.
The example below first sets a variable $i to one ($i = 1). Then, the while loop runs as long as $i is
less than seven ($i < 7). $i will increase by one each time the loop runs ($i++):
$i = 1;
The do...while loop will always execute the block of code once, check the condition, and repeat the
loop as long as the specified condition is true.
Syntax:do {
code to be executed;
Regardless of whether the condition is true or false , the code will be executed at least once ,
The example below will write some output, and then increment the variable $i by one. Then the
condition is checked, and the loop continues to run, as long as $i is less than or equal to 7.
$i = 5;
do {
$i++;
//The number is 5
//The number is 6
//The number is 7
Note that in a do while loop, the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
The for loop is used when you know in advance how many times the script should run.for (init;
test; increment) {
code to be executed;
}
Parameters:
init: Initialize the loop counter value
test: Evaluates each time the loop is iterated, continuing if evaluates to true, and ending if it
evaluates to false
increment: Increases the loop counter value
Each of the parameter expressions can be empty or contain multiple expressions that are
for (expr1)
for (expr1; expr2)
for (expr1; expr2; expr3)
Result:
The for loop in the example above first sets the variable $a to 0, then checks for the condition
($a < 6). If the condition is true, it runs the code. After that, it increments $a ($a++).
// John
// David
// Amy
Syntax:switch (n) {
case value1:
break ;
case value2:
break ;
...
default :
}
First, our single expression, n (most often a variable), is evaluated once. Next, the value of the
expression is compared with the value of each case in the structure. If there is a match, the block
of code associated with that case is executed.
Using nested if else statements results in similar behavior, but switch offers a more elegant
while loop
do while loop
if elseif else statement
Consider the following example, which displays the appropriate message for each day.
$today = 'Tue';
switch ($today) {
case "Mon":
break ;
case "Tue":
break ;
case "Wed":
break ;
case "Thu":
break ;
case "Fri":
break ;
case "Sat":
echo "Today is Saturday.";
break ;
case "Sun":
break ;
default :
The break keyword that follows each case is used to keep the code from automatically running
into the next case. If you forget the break; statement, PHP will automatically continue through the
next case statements, even when the case doesn't match.
default
$x=5;
switch ($x) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
default:
echo "No match";
What keyword is used to handle cases that are not defined with the case
keyword?
==> default
Failing to specify the break statement causes PHP to continue to executing the statements that
follow the case, until it finds a break. You can use this behavior if you need to arrive at the same
output for more than one case.
$day = 'Wed';
switch ($day) {
case 'Mon':
break ;
case 'Tue':
case 'Wed':
case 'Thu':
break ;
case 'Fri':
echo 'Friday!';
break ;
default :
echo 'Weekend!';
The example above will have the same output if $day equals 'Tue', 'Wed', or 'Thu'.
Winter
Nothing
Summer
$x=1;
switch ($x) {
case 1:
echo "One";
case 2:
echo "Two";
case 3:
echo "Three";
default:
continues to run the program on the line coming up after the loop.
A break statement in the outer part of a program (e.g., not in a control loop) will stop the script.
The continue Statement
When used within a looping structure, the continue statement allows for skipping over what
remains of the current loop iteration. It then continues the execution at the condition evaluation
and moves on to the beginning of the next iteration.
if ($i%2==0) {
continue ;
//Output: 1 3 5 7 9
include
The include and require statements allow for the insertion of the content of one PHP file into
another PHP file, before the server executes it.
Including files saves quite a bit of work. You can create a standard header, footer, or menu file for
all of your web pages. Then, when the header is requiring updating, you can update the header
include file only.
echo '<h1>Welcome</h1>';
?>
<body>
<?php include 'header.php'; ?>
<p>Some text.</p>
<p>Some text.</p>
</body>
</html>
The include and require statements allow for the insertion of the content of one PHP file into
#include <file.php>
include-file.php;
include 'file.php';
Using this approach, we have the ability to include the same header.php file into multiple pages.
<html>
<body>
<p>This is a paragraph</p>
</body>
</html>
Result:
You can use an absolute or a relative path to specify which file should be included.
include vs require
The require statement is identical to include, the exception being that, upon failure, it produces a
fatal error.
When a file is included using the include statement, but PHP is unable to find it, the script
continues to execute.
In the case of require, the script will cease execution and produce an error.
Use require when the file is required for the application to run.
Use include when the file is not required. The application should continue, even when the file is
not found.
There is no difference
The syntax is different
The way they handle errors
What output results from the following code?
$x = 0;
while($x<=7) {
$x++;
}
echo $x;
==> 8
False
True
Functions
function functionName() {
//code to be executed
}
A function name can start with a letter or an underscore, but not with a number or a special
symbol.
Function names are NOT case-sensitive.
#hello()
123()
_hello()
11_hello()
In the example below, we create the function sayHello(). The opening curly brace ({) indicates that
this is the beginning of the function code, while the closing curly brace (}) indicates that this is the
end.
To call the function, just write its name:
function sayHello() {
echo "Hello!";
//Outputs "Hello!"
Function Parameters
function multiplyByTwo($number) {
$answer = $number * 2;
echo $answer;
multiplyByTwo(3);
//Outputs 6
You can add as many arguments as you want, as long as they are separated with commas.
//Outputs 18
When you define a function, the variables that represent the values that will be passed to it for
processing are called parameters. However, when you use a function, the value you pass to it is
called an argument.
Default Arguments
setCounter(42); //Counter is 42
setCounter(); //Counter is 10
When using default arguments, any defaults should be on the right side of any non-default
arguments; otherwise, things will not work as expected.
Return
return $res;
// Outputs 24
Fill in the blanks to declare a function myFunction, taking two parameters and
printing the product of their multiplication to the screen.
function myFunction($a, $b) {
echo $a * $b;
}
Predefined Variables
A superglobal is a predefined variable that is always accessible, regardless of scope. You can
access the PHP superglobals through any function, class, or file.
PHP's superglobal variables are $_SERVER, $GLOBALS, $_REQUEST, $_POST, $_GET, $_FILES,
$_ENV, $_COOKIE, $_SESSION.
$_SERVER
$_SERVER is an array that includes information such as headers, paths, and script locations. The
entries in this array are created by the web server.
$_SERVER['SCRIPT_NAME'] returns the path of the current script:
<?php
echo $_SERVER['SCRIPT_NAME'];
//Outputs "/somefile.php"
?>
Our example was written in a file called somefile.php, which is located in the root of the web
server.
echo $_SERVER['HTTP_HOST'];
//Outputs "localhost"
?>
This method can be useful when you have a lot of images on your server and need to transfer the
website to another host. Instead of changing the path for each image, you can do the following:
Create a config.php file, that holds the path to your images:
<?php
$host = $_SERVER['HTTP_HOST'];
$image_path = $host.'/images/';
?>
require 'config.php';
?>
The path to your images is now dynamic. It will change automatically, based on the Host header.
A function
An integer
An array
A string
Forms
The purpose of the PHP superglobals $_GET and $_POST is to collect data that has been entered
into a form.
The example below shows a simple HTML form that includes two input fields and a submit button:
<form action=" first.php " method=" post ">
</form>
Result:
The purpose of the PHP superglobals $_GET and $_POST is to collect data that has been entered
into a form.
Which HTML element is needed to collect user input from a web page?
form
div
hr
table
The action attribute specifies that when the form is submitted, the data is sent to a PHP file
named first.php.
HTML form elements have names, which will be used when accessing the data with PHP.
The method attribute will be discussed in the next lesson. For now, we'll set the value to
Which form attribute indicates the page to which the form is submitted?
Submit
Method
Action
Input
Now, when we have an HTML form with the action attribute set to our PHP file, we can access the
posted form data using the $_POST associative array.
In the first.php file:
<html>
<body>
Welcome <?php echo $_POST["name"] ; ?><br />
</body>
</html>
The $_POST superglobal array holds key/value pairs. In the pairs, keys are the names of the form
controls and values are the input data entered by the user.
We used the $_POST array , as the method="post " was specified in the form.
POST
Fill in the blanks to print the value of a text box named "email", which was
submitted using POST.
<?php
echo $_POST["email"];
?>
GET
Information sent via a form using the GET method is visible to everyone (all variable names and
values are displayed in the URL). GET also sets limits on the amount of information that can be
sent - about 2000 characters.
However, because the variables are displayed in the URL, it is possible to bookmark the page,
which can be useful in some situations.
For example:
<form action="actionGet.php" method=" get ">
</form>
actionGet.php
<?php
?>
Now, the form is submitted to the actionGet.php, and you can see the submitted data in the URL:
GET should NEVER be used for sending passwords or other sensitive information!
When using POST or GET, proper validation of form data through filtering and processing is
vitally important to protect your form from hackers and exploits!
Which method was used for the following URL?
http://www.sololearn.com/index.php?id=825
POST
GET
Sessions
Using a session, you can store information in variables, to be used across multiple pages.
Information is not stored on the user's computer, as it is with cookies.
By default, session variables last until the user closes the browser.
$_SESSION['color'] = "red";
$_SESSION['name'] = "John";
?>
Now, the color and name session variables are accessible on multiple pages, throughout the entire
session.
The session_start() function must be the very first thing in your document. Before any HTML
tags.
Type in the function that must be called before working with the session
variables.
session_start();
Session Variables
Another page can be created that can access the session variables we set in the previous page:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Your session variables remain available in the $_SESSION superglobal until you close your
session.
All global session variables can be removed manually by using session_unset() . You can also
Rearrange the code to declare the variable name, add it to the session, and
then print it to the screen.
session_start();
$name = "Alex";
$_SESSION['name'] = $name;
echo $_SESSION['name'];
Cookies
Cookies are often used to identify the user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page through a browser, it will send
the cookie, too. With PHP, you can both create and retrieve cookie values.
On the server
On the user's computer
They are not stored
The following example creates a cookie named "user" with the value "John". The cookie will expire
after 30 days, which is written as 86,400 * 30, in which 86,400 seconds = one day. The '/' means
that the cookie is available throughout the entire website.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use
the isset() function to find out if the cookie is set:
<?php
$value = "John";
if(isset($_COOKIE['user'])) {
?>
The value of the cookie is automatically encoded when the cookie is sent, and is automatically
decoded when it's received. Nevertheless, NEVER store sensitive information in cookies.
Fill in the blanks to set a cookie named 'logged' with the value 1 and an
expiration time of 1 hour.
setcookie('logged', 1, time()+3600);
Which of the form submit methods should be chosen for a login page?
GET
POST
Yes
No
Manipulating Files
PHP offers a number of functions to use when creating, reading, uploading, and editing files.
The fopen() function creates or opens a file. If you use fopen() with a file that does not exist, the
file will be created, given that the file has been opened for writing (w) or appending (a).
The example below creates a new file, "file.txt", which will be created in the same directory that
houses the PHP code.
PHP offers a number of functions to use when creating, reading, uploading, and editing files.
Write to File
The example below writes a couple of names into a new file called "names.txt".
<?php
$txt = "John\n";
$txt = "David\n";
fclose($myfile);
/* File contains:
John
David
*/
?>
Notice that we wrote to the file "names.txt" twice, and then we used the fclose() function to close
the file.
The \n symbol is used when writing new lines .
fclose()
The fclose() function closes an open file and returns TRUE on success or FALSE on failure.
It's a good practice to close all files after you have finished working with them.
Appending to a File
If you want to append content to a file, you need to open the file in append mode.
For example:
$myFile = "test.txt";
$fh = fopen($myFile, 'a');
fwrite($fh, "Some text");
fclose($fh);
When appending to a file using the 'a' mode , the file pointer is placed at the end of the file,
ensuring that all new data is added at the end of the file.
Which of the following is not a supported file access mode for the fopen
function?
d
a
r
w
Let's create an example of a form that adds filled-in data to a file.
<?php
if(isset($_POST['text'])) {
$name = $_POST['text'];
fwrite($handle, $name."\n");
fclose($handle);
?>
<form method="post">
</form>
Now, each time a name is entered and submitted, it's added to the "names.txt" file, along with a
new line.
The isset() function determined whether the form had been submitted, as well as whether the text
contained a value.
We did not specify an action attribute for the form, so it will submit to itself.
Reading a File
The file() function reads the entire file into an array. Each element within the array corresponds to
a line in the file:
This prints all of the lines in the file, and separates them with commas.
We used the foreach loop, because the $read variable is an array .
Which function is used to read the content of a file?
file()
read()
read_file()
At the end of the output in the previous example, we would have a comma, as we print it after each
element of the array.
The following code lets us avoid printing that final comma.
$read = file('names.txt');
$count = count($read);
$i = 1;
echo $line;
$i++;
The $count variable uses the count function to obtain the number of elements in the $read array.
Then, in the foreach loop, after each line prints, we determine whether the current line is less than
the total number of lines, and print a comma if it is.
This avoids printing that final comma, as for the last line, $i is equal to $count.
Which function was used to get the number of elements in the array?
==> count
fopen("time.txt","r");
fopen("times.txt", "d");
open("time.txt","read");
open("time.txt");
Here, Building is a class. It defines the features of a generic building and how it should work.
The Empire State Building is a specific object (or instance) of that class.
You can use the same class as a blueprint for creating multiple different objects.
False
True
PHP Classes
In PHP, a class can include member variables called properties for defining the features of an
object, and functions, called methods, for defining the behavior of an object. A class definition
begins with the keyword class, followed by a class name. Curly braces enclose the definitions of
the properties and methods belonging to the class.
For example:
class Person {
echo "Hi!"
}
The code above defines a Person class that includes an age property and a speak() method.
A valid class name starts with a letter or underscore, followed by any number of letters, numbers,
or underscores.
Notice the keyword public in front of the speak method; it is a visibility specifier.
The public keyword specifies that the member can be accessed from anywhere in the code.
There are other visibility keywords and we will learn about them in later lessons.
Check out the next lesson to see how to instantiate objects !
PHP Objects
To access the properties and methods of an object, use the arrow (->) construct, as in:
Let's define the Person class, instantiate an object, make an assignment, and call the speak()
method:
class Person {
public $age;
function speak() {
echo "Hi!";
Output: 23Hi!
$this
$this is a pseudo-variable that is a reference to the calling object. When working within a method,
use $this in the same way you would use an object name outside the class.
For example:
class Dog {
public $legs=4;
$d1->display(); //4
$d2->legs = 2;
$d2->display(); //2
Output:
4
2
We created two objects of the Dog class and called their display() methods. Because the display()
method uses $this, the legs value referred to the appropriate calling object’s property value.
As you can see, each object can have its own values for the properties of the class.
PHP provides the constructor magic method __construct(), which is called automatically whenever
a new object is instantiated.
For example:
class Person {
$p = new Person();
The __construct() method is often used for any initialization that the object may need before it is
used. Parameters can be included in __construct() to accept values when the object is created.
For example:
class Person {
public $name;
public $age;
$this->name = $name;
$this->age = $age;
Output: David
In the code above, the constructor uses arguments in the new statement to initialize
corresponding class properties.
You can't write multiple __construct() methods with different numbers of parameters. Different
constructor behavior must be handled with logic within a single __construct() method.
class Person {
$p = new Person();
This script creates a new Person object. When the script ends the object is automatically
destroyed, which calls the destructor and outputs the message "Object destroyed".
To explicitly trigger the destructor, you can destroy the object using the unset() function in a
statement similar to: unset($p);
Destructors are useful for performing certain tasks when the object finishes its lifecycle. For
example, release resources, write log files, close a database connection, and so on.
2
21
12
1
Classes can inherit the methods and properties of another class. The class that inherits the
methods and properties is called a subclass. The class a subclass inherits from is called
the parent class.
class Animal {
public $name;
$d = new Dog();
$d->hi();
Here the Dog class inherits from the Animal class. As you can see, all the properties and methods
of Animal are accessible to Dog objects.
Parent constructors are not called implicitly if the subclass defines a constructor. However, if the
child does not define a constructor then it will be inherited from the parent class if it is not
declared private.
Notice all our properties and methods have public visibility.
For added control over objects, declare methods and properties using a visibility keyword. This
controls how and from where properties and methods can be accessed.
PHP Visibility
Class properties must always have a visibility type. Methods declared without any explicit visibility
keyword are defined as public.
Protected members are used with inheritance.
Which of the following defines a visibility control allowing access only from
subclasses?
final
invisible
protected
private
PHP Interfaces
<?php
interface AnimalInterface {
$myObj1->makeSound();
$myObj2->makeSound();
?>
Output:
Woof!
Meow!
A class can implement multiple interfaces. More than one interfaces can be specified by
separating them with commas. For example:
}
An interface can be inherit another interface by using the extends keyword.
All the methods specified in an interface require public visibility.
A class inheriting from an abstract class must implement all the abstract methods.
The abstract keyword is used to create an abstract class or an abstract method.
For example:
<?php
$this->color = $c;
echo "Omnomnom";
$obj->eat();
?>
Output: Omnomnom
Abstract functions can only appear in an abstract class.
A static property or method is accessed by using the scope resolution operator :: between the
class name and the property/method name.
For example:
<?php
class myClass {
?>
Output: 42
The self keyword is needed to access a static property from a static method in a class definition.
For example:
<?php
class myClass {
myClass::myMethod();
?>
Output: 42
Objects of a class cannot access static properties in the class but they can access static methods.
The final Keyword
The PHP final keyword defines methods that cannot be overridden in child classes. Classes that
are defined final cannot be inherited.
This example demonstrates that a final method cannot be overridden in a child class:
<?php
class myClass {
echo "Parent";
}
// ERROR because a final method cannot be overridden in child classes.
class myClass2 extends myClass {
function myFunction() {
echo "Child";
?>
Output: Fatal
error: Cannot override final method myClass::myFunction()
in ./Playground/file0.php on line 9
<?php
}
// ERROR because a final class cannot be inherited.
?>
Fill in the blanks to define a "Father" class with a final method useMoney()
that cannot be overridden in its "Son" subclass.
class Father {
final function useMoney() {
echo "wisely";
}
}
class Son extends Father {
public function sayHi() {
echo "Hi!";
}
}
declaration
creation
instantiation
execution
public
protected
this
final
The Foo() method cannot be overridden in a child class. Why?
class A {
final function Foo() {
echo "A";
}
}
class B extends A {
function Foo() {
echo "B";
}
}