0% found this document useful (0 votes)
7 views

PHP 2 Marks Final Draft

Uploaded by

sandhyabks8113
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PHP 2 Marks Final Draft

Uploaded by

sandhyabks8113
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

//SH

1. Give the syntax and example for defining a user-defined function in PHP.
Ans: To define a function, use the following syntax:
function [&] function_name([parameter[, ...]])
{
statement list
}
The statement list can include HTML. You can declare a PHP function that doesn’t
contain any PHP code. For instance, the column() function simply gives a
convenient short name to HTML code that may be needed many times throughout
the page:

2. Differentiate between formal parameters and actual parameters in PHP


functions.
Ans:
//GPT
In PHP, when defining a function, you specify formal parameters (also known
as function parameters or parameters) in the function signature. These are the
variables that will receive the values passed to the function when it's called.
On the other hand, when calling a function, you pass actual parameters (also known
as arguments) to the function. These are the values that are assigned to the formal
parameters.

3. What is function scope in PHP?


Ans: The variables defined in a function, including its parameters, are not accessible
outside
the function, and, by default, variables defined outside a function are not accessible
inside the function. The following example illustrates this:
$a = 3;
function foo()
{$a += 2;
}
foo();
echo $a;
The variable $a inside the function foo() is a different variable than the variable $a
outside the function; even though foo() uses the add-and-assign operator, the value
of
the outer $a remains 3 throughout the life of the page.
4. What happens if you call a PHP function with fewer arguments than declared in
its definition?
Ans:
//GPT
When you call a PHP function with fewer arguments than declared in its definition,
PHP will use the default values for the missing arguments, if they are defined. If no
default values are defined, PHP will throw a warning.

5. Describe the concept of default parameter values in PHP functions.


In PHP, a default parameter refers to a value set for a function parameter that will be
used if no argument is provided for that parameter when the function is called. To
specify a default parameter, assign the parameter value in the function declaration.
The value assigned to a parameter as a default value cannot be a complex
expression;
it can only be a scalar value:
function getPreferences($whichPreference = 'all')
{
// if $whichPreference is "all", return all prefs;
// otherwise, get the specific preference requested...
}
When you call getPreferences(), you can choose to supply an argument. If you do, it
returns the preference matching the string you give it; if not, it returns all
preferences.

6. How do you access global variables within a PHP function? Give example
Ans: If you want a variable in the global scope to be accessible from within a
function, you can use the global keyword. Its syntax is:
global var1, var2, ...
Changing the previous example to include a global keyword, we get:

Instead of creating a new variable called $a with function-level scope, PHP uses the
global $a within the function. Now, when the value of $a is displayed, it will be 5.

7. What is “pass by value" in the context of PHP function parameters.


Ans: (GPT)
In PHP, "pass by value" refers to the method of passing arguments to a function
where the value of the argument is copied into the function's parameter. This means
that changes made to the parameter inside the function do not affect the original
value of the variable passed to the function

//MA
8. What is "pass by reference" in PHP function parameters?
Ans:
Passing by reference allows you to override the normal scoping rules and give a
function direct access to a variable. To be passed by reference, the argument must
be a variable; you indicate that a particular argument of a function will be passed by
reference by preceding the variable name in the parameter list with an ampersand
(&).
Eg:
9. What is Default Parameter in PHP functions? Give example
Ans:
Sometimes a function may need to accept a particular parameter. For example,
when you call a function to get the preferences for a site, the function may take in a
parameter with the name of the preference to retrieve. Rather than using some
special keyword to designate that you want to retrieve all of the preferences, you can
simply not supply any argument. This behavior works by using default argument
Eg:
function getPreferences($whichPreference = 'all')
{ // if $whichPreference is "all", return all prefs;
// otherwise, get the specific preference requested...
}

10. How to check missing parameters in PHP functions ? Give example


PHP lets you be as lazy as you want—when you call a function, you can pass any
number of arguments to the function. Any parameters the function expects that are
not passed to it remain unset, and a warning is issued for each of them:
Eg:
function takesTwo($a, $b)
{
if (isset($a))
{
echo " a is set\n";
}
if (isset($b))
{
echo " b is set\n";
}
}
echo "With two arguments:\n"; takesTwo(1, 2);
echo "With one argument:\n"; takesTwo(1);

11. What are anonymous functions ? Give examples


Some PHP functions use a function you provide them with to do part of their work.
For example, the usort() function uses a function you create and pass to it as a
parameter to determine the sort order of the items in an array. Although you can
define a function for such purposes, as shown previously, these functions tend to be
localized and temporary. To reflect the transient nature of the callback, create and
use an anonymous function (also known as a closure). You can create an anonymous
function using the normal function definition syntax, but assign it to a variable or
pass it directly.
Eg:

12. Differentiate single quoted and double quoted strings in PHP?


Ans:
Single-quoted strings do not interpolate variables. Thus, the variable name in the
following string is not expanded because the string literal in which it occurs is single
quoted:
Eg:
$name = 'Fred';
$str = 'Hello, $name'; // single-quoted
echo $str;
Hello, $nam
Double-quoted strings interpolate variables and expand the many PHP escape
sequences. lists the escape sequences recognized by PHP in double-quoted strings.
Eg:
$str = "What is \c this?";// unknown escape sequence
echo $str;
What is \c this?

13. What is variable interpolation?Give example


Ans: When you define a string literal using double quotes or a heredoc, the string is
subject to variable interpolation. Interpolation is the process of replacing variable
names in the string with the values of those variables. There are two ways to
interpolate variables into strings.
The simpler of the two ways is to put the variable name in a double-quoted string or
heredoc:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";
Kilroy was her

//AB
14. Explain the two ways to interpolate variables into strings?
= The simpler of the two ways is to put the variable name in a double-quoted string
or heredoc:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";
Kilroy was here
The other way is to surround the variable being interpolated with curly braces. Using
this syntax ensures the correct variable is interpolated. The classic use of curly
braces is to disambiguate the variable name from surrounding text:
$n = 12; echo "You are the {$n}th person";
You are the 12th person
Without the curly braces, PHP would try to print the value of the $nth variable.
PHP strings are not repeatedly processed for interpolation. Instead, any
interpolations in a double-quoted string are processed first and the result is used as
the value of the string:
$bar = 'this is not printed'; $foo = '$bar';
// single quotes print("$foo");
$bar

15. What are Here Documents in PHP? Give example.


= The <<< identifier token tells the PHP parser that you’re writing a heredoc. There
must be a space after the <<< and before the identifier. You get to pick the identifier.
The next line starts the text being quoted by the heredoc, which continues until it
reaches a line that consists of nothing but the identifier.
As a special case, you can put a semicolon after the terminating identifier to end the
statement, as shown in the previous code. If you are using a heredoc in a more
complex expression, you need to continue the expression on the next line, as shown
here:
printf(<<< Template
%s is %d years old.
Template
, "Fred", 35);
Single and double quotes in a heredoc are passed through:
$dialogue = <<< NoMore
"It's not going to happen!" she fumed.
He raised an eyebrow. "Want to bet?"
NoMore;
echo $dialogue;

16. Differentiate echo and print statement in PHP?


The echo construct lets you print
many values at once, while print() prints only one value

The print() construct sends one value (its argument) to the browser:
if (print("test")) {
print("It worked!");
}
It worked!

You can specify multiple items to print by separating them with commas using echo
echo "First", "second", "third";

17. What is the use of print_r() statement? Give example.


= The print_r() construct intelligently displays what is passed to it, rather than casting
everything to a string, as echo and print() do. Strings and numbers are simply printed.
Arrays appear as parenthesized lists of keys and values, prefaced by Array:
$a = array('name' => 'Fred', 'age' => 35, 'wife' => 'Wilma');
print_r($a);
Output: Array ( [name] => Fred [age] => 35 [wife] => Wilma)
When you print_r() an object, you see the word Object, followed by the initialized
properties of the object displayed as an array.

18. What is type specifiers? List the printf type specifiers.


=The type specifier tells printf() what type of data is being substituted. This
determines the interpretation of the previously listed modifiers.
19. What is the use of var_dump() statement? Give example.
= The var_dump() function displays any PHP value in a human-readable format:
//two examples are enough
var_dump(true);
Output: bool(true)
var_dump(1);
Output: int(1)

var_dump(array('name' => "Fred", 'age' => 35));


Output: array(2) { ["name"]=> string(4) "Fred" ["age"]=> int(35) }

//DJ
20. Explain trim function in php along with its types?
trim() returns a copy of string with whitespace removed from the beginning and the
end. ltrim() (the l is for left) does the same, but removes whitespace only from the
start of the string. rtrim() (the r is for right) removes whitespace only from the end of
the string.
21. How can you include one PHP file into another PHP file?
We can include one PHP file in another by using the include statement. Syntax is
include “filename.php”;
example if we create a file as connection.php with the code of database connection
it can be used in any other PHP file using include “connection.php”;
22. Name three commonly used PHP string manipulation functions.
substr() function
strrev() function
str_repeat() function
str_pad() function
explode() function
implode() function
23. Explain strcasecmp() with example?
Its is a variation on strcmp() , converts strings to lowercase before comparing them.
Its arguments and return values are the same as those for strcmp():
Eg: $n = strcasecmp("Fred", "frED");
Compares two strings; returns a number less than 0 if one is less than two, 0 if the
two strings are equal, and a number greater than 0 if one is greater than two. The
comparison is case insensitive—that is, “Alphabet” and “alphabet” are considered
equal.
24. Differentiate strncmp() and strncasecmp() in php?
strncmp():
$relationship = strcmp(string_1, string_2);
The function returns a number less than 0 if string_1 sorts before string_2, greater
than 0 if string_2 sorts before string_1, or 0 if they are the same
strcasecmp():
which converts strings to lowercase before comparing them. Its arguments and
return values are the same as those for strcmp():
$n = strcasecmp("Fred", "frED");
25. Write the syntax of substr_count() PHP with example
Syntax:
$number = substr_count(big_string, small_string);

//AN
26. Write the syntax of substr_replace() PHP with example
The substr_replace() function permits many kinds of string modifications:
$string = substr_replace(original, new, start [, length ]);
The function replaces the part of original indicated by the start (0 means the start of
the string) and length values with the string new. If no fourth argument is given,
substr_replace() removes the text from start to the end of the string.
For instance:
$greeting = "good morning citizen";
$farewell = substr_replace($greeting, "bye", 5, 7);
// $farewell is "good bye citizen"

27. What is the purpose of the substr() function in PHP? Give example
you can copy it out with the substr() function:
$piece = substr(string, start [, length ]);
The start argument is the position in string at which to begin copying, with 0 meaning
the start of the string. The length argument is the number of characters to copy (the
default is to copy until the end of the string). For example:
$name = "Fred Flintstone";
$fluff = substr($name, 6, 4); // $fluff is "lint"
$sound = substr($name, 11); // $sound is "tone"

28. How can you concatenate strings in PHP?


Give example
String concatenation uses the period (.) to append one string of characters
toanother. The simplest way to do this is as follows:
echo "You have " . $msgs . " messages.";

29. List two PHP library function for handling date and time.
//gpt
date()
strtotime():

30. How do you create an instance of a class in PHP? Give example


To create an object with a specified class, use the new keyword, like this: object=
new Class. Here are a couple of ways in which we could do this:
$object = new User;
$temp = new User('name', 'password');

31. How you access object properties in PHP ? Give example


the syntax for accessing an object’s property is $object->property. Likewise, you call
a method like this: $object->method().

//VSS
32. Define overloading in the context of PHP classes.
//gemini

In PHP, overloading is different from traditional object-oriented overloading. It's


about dynamically creating properties and methods using magic methods.

These methods handle interactions with properties or methods that aren't explicitly
defined within the class.
33. What is a constructor in PHP classes? How it is declared ?
A special function that initializes the properties of the class is called as constructor.
A constructor is a function in the class called __construct(). Here’s a constructor for
the Person class:
class Person
{
function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}

34. What is a destructor in PHP classes? How it is declared?


When an object is destroyed, such as when the last reference to an object is
removed
or the end of the script is reached, its destructor is called. Because PHP
automatically
cleans up all resources when they fall out of scope and at the end of a script’s
execution,
their application is limited. The destructor is a method called __destruct():
class Building
{
function __destruct()
{
echo "A Building is being destroyed!";
}
}

35. How do you access object properties and methods within a class in PHP? Give
example
Once you have an object, you can use the -> notation to access methods and
properties
of the object:
$object->propertyname
$object->methodname([arg, ... ])
For example:
echo "Rasmus is {$rasmus->age} years old.\n"; // property access
$rasmus->birthday(); // method call
$rasmus->setAge(21); // method call with arguments
Methods act the same as functions (only specifically to the object in question), so
they
can take arguments and return a value:
$clan = $rasmus->family("extended");

36. What is a trait in PHP, and how does it differ from classes and interfaces?
Traits
Traits provide a mechanism for reusing code outside of a class hierarchy. Traits
allow
you to share functionality across different classes that don’t (and shouldn’t) share a
common ancestor in a class hierarchy.
//gpt
While a class can only inherit from one parent class, it can use multiple traits
simultaneously.

37. What is introspection in PHP ?


Introspection is the ability of a program to examine an object’s characteristics, such
as its name, parent class (if any), properties, and methods. With introspection, you
can write code that operates on any class or object. You don’t need to know which
methods or properties are defined when you write your code; instead, you can
discover that information at runtime, which makes it possible for you to write generic
debuggers, serializers, profilers, etc..

You might also like