<?php ?>
tell php parser to start and stop
<% %>
, <script language=php >
are deployed in previous versions
<? ?>
it is not preferable, need to change short_open_tag in php.ini
<?php echo "welcome to php"; ?>
<?php ‘welcome to php’ ?>
//comments
/* block comments*/
#shell comments
__halt_compiler(), abstract, and, array, as, break, callable, case, catch, class, clone, const, continue, declare, default, die(), dom, echo, else, elseif, empty(), enddeclare, endfor, endforeach, endif, endswitch, endwhile, eval(), exit(), extends, final, finally, for, foreach, function, global, goto, include_once, instanceof, insteadof, interface, isset, list, namespace, new, or, print, private, protected, public, require, require_once, return, static, switch, throw, trait, try, unset, use, var, while, xor, yield
$string = <<<EOK rajesh EOK;
resource - special data type, represent a PHP extension resource such as a database query, an open file, a database connection, and lots of other external types. You will never directly use this type, but will pass to the relevant functions
Indirect reference variable: $name="rajesh"; $$name="good boy"; echo $rajesh;
we can declare variable without variable name. //$var; #### Important functions:
$GLOBALS[] $name="rajesh";
function getname(){
echo $GLOBALS['name']; //access outer variable inside function
}getname();
<?php
$foo = "1"; // $foo is string (ASCII 49)
$foo =$foo * 2; // $foo is now an integer (2)
$foo = $foo * 1.3; // $foo is now a float (2.6)
$foo = 5 * "10 Little Piggies"; // $foo is integer (50)
$foo = 5 * "10 Small Pigs"; // $foo is integer (50)
?>
(globally accessible)
`define(‘VAR_NAME,’rajesh’);`
`const VAR_NAME = ‘rajesh’;` - should be called without object using scope resolution operator. eg.ClassName::VAR_NAME; - while extends, it is called using PARENT::var_name , - we need SELF::var_name instead of $this->var_name while using in same class
__LINE__
return line number__FILE__
return filename__DIR__
return directory__FUNCTION__
return function name__CLASS__
return classname__TRAIT__
return trait name__METHOD__
return classname and function name__NAMESPACE__
return namespace nameBitwise operator - &(and), | (or),^(xor),~(not),«(swift left),»(swift right) |
)Logical operator – and,or,!,xor,&&, |
if ( condition ){
body;
}
if ( condition ){
body;
} else {
body;
}
if ( condition ){
body;
} elseif ( condition ){
body;
} else {
body;
}
switch ( expression ) {
case value1:
statement;
break;
case default:
statement;
}
expression ? Statement1 : statement2;
php
for ( intialisation; condition; inc/dec) {
body;
}
while ( condition ) {
body;
}
do {
body;
} while ( condition )
foreach ( $arrayname as $var) { //foreach with value
body;
}
foreach ( $arrayname as $key => $var){ //foreach with reference
body; //we can use $key
}
goto varname; continue;
function functionname ( $varname ) { body;}
function functionname ( &$varname ) { body;}
function functionname ( ...$varname ) { body; }
function functionname ($varname=0) {body;}
Note: same function name should not repeat in php
function &get_global_variable($name) {
return $GLOBALS[$name];
}
$num = 10;
$value =& get_global_variable("num");
print $value . "\n";
$value = 20;
print $num;
$obj->func1()->func2();
// func1 should return $thistext files stored on client computer
setcookie(“cookiename”,”cookevalue”,”expirytime”,path,url,https,httponly);
secure way –> setcookie(“cookiename”,”cookevalue”,”expirytime”,’/’,null,null,true);
eg: setcookie("name","rajesh","time()-3600");
$_COOKIE("cookiename");
setcookie("cookiename",null,expirytime);
creates file in a temp folder in server, 32 hexadecimal number as unique id. A cookie called PHPSESSID is sent to client browser,
session_start(); session_destroy(); $_SESSION[‘varname’]="deep";
superGlobals:
- $_GET[‘varname’];
- $_POST[‘varname’];
- $_REQUEST[‘varname’];
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image">
$_FILES[‘image’][‘name’],
$_FILES[‘image’][‘type’]
$_FILES[‘image’][‘size’]
move_upload_file($_FILES[‘image’][‘temp_name’],’target path’);
template to make object, blueprint of properties and behaviours
class className{
function __construct(){ //it is called when $obj = new className()
}
function __destruct(){ //it is called when $obj=null;
}
function __clone(){ //it is called when using clone keyword
}
}
$this – refer property of current class
instance of class
$obj = new className();
$obj->varnames; $obj->function();
cloning object: use clone keyword before object to be copied. eg $obj2= clone obj1;
| | Same class | Derived | outside | |———–|————|———–|———–| |public | yes | yes | yes | |private | yes | no | no | |protected | yes | yes | no | ————————————————–
ex:can maintain count how many objects created for the class by incrementing each time.
- can call without creating object with scope resolution operator.
- We can declare static as private and protected
public static $varname;
public static functionname(){
return obj; return staticvariable; } //should not return normal variable,becz there will be no obj,so cant use $this->variablename
Note: Dont use $this for static, its error
multilevel inheritance(extend by more than one child)
abilty to define method in many forms
keyword will avoid overriding //act as super keyword
hiding the implementation
- have abstract and non abstract function ```php
abstract classname{ //abstract class must have atleast one abstract class
abstract function funcname(); // have only function declaration not defination
function func2(){..... with defination.....}
} ```
100% abstraction, implements to child class. all function should public
interface fruit{
function funcname();
}
class apple implments fruit{
function funcname(){.....}
}
same like abstract interface.(for multiple inheritance)
trait A{
function functionname();----}
class B{
user A;}
$obj = new B(); obj->functionname();
$variableName = function(){----};
$obj = (new class{-----functions and vairiables-----});
can use same name function and class
namespace namespacename;
class class1{ }
function func1(){------}
$obj = new \namespacename\class1(); //creating object using namespace
\namespacename\func1(): //function calling using namespace
$conn =mysqli_connect(‘localhost’,’root’,’password’,’dbname’);
$result= mysqli_query($conn,$query);
echo mysqli_num_rows($result); //return num of rows
$row=mysqli_fetch_array($result,MYSQLI_BOTH); // MYSQLI_NUM // MYSQLI_ASSOC
$obj=mysqli_fetch_obj($result);
$row=mysqli_fetch_row($result);
$mysqliObj = new mysqli(‘localhost’,’usrename’,’password’,’dbname’);
$result=$mysqli->query($query);
$row=$result->fetch_array($query);
$lastid = mysqli_insert_id($conn);
import file having below function, and create object directly use it
spl_autoload_register(function($var){
include $var.’php’;
});
spl_autoload_register('functionName'); //write the loader function seperately
function __autoload($funName){
require_once($_SERVER["DOCUMENT_ROOT"] . "/classes/$class_name.php")
}
can use same class/function name in same file
namespace class1;
class Hello{} function Hii(){}
namespace class2;
class Hello{} function Hii(){}
$obj = new class1\Hello(); class1\Hii():
$obj = new class2\Hello(); class1\Hii():
mail($to,$subject,$body,$header);
simplexml_load_file(‘xmlfile’);
encode(), decode
serialize($obj); unserialize(string); //make the obj into string, and we can use it with own values
THROWABLE
ERROR -notice,fatal,warning
Arithmatic Error
divisionByZeroError
AssertionError
ParseError
TypeError
EXCEPTION
ClosedGeneralException
DOMException
ErrorException
IntlException
LogicException
BadFunctionalException
BadMethodcallException
Domain exception
invalid arguement exeception
Lengthexception
OutOfRangeException
pharException
ReflectionException
Runtime Exception
mysqli_sql_exception
outOfBoundException
OverflowException
PDOException
RangeException
UnderFlowException
UnExpectedValueException
try{
}
catch (Exception $e){ var_dump($e->getTrace();)
}
Custom exception:
try{
throw new rajeshexception();
}
catch (rajeshException $e){ }
header('Content-type: text/json');
echo json_encode(array("name"=>"rajesh"));
$xml = new SimpleXMLElement("<student />");
$xml->addChild("name","rajesh");
$xml->addChild("age","23");
$dom = dom_import_simplexml($xml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();
<?xml version="1.0"?>
<student>
<name>rajesh</name>
<age>23</age>
</student>