Skip to content

Instantly share code, notes, and snippets.

@zahra-ove
Last active May 17, 2024 07:42
Show Gist options
  • Save zahra-ove/d35c17fc031a25a8d873dcd5cd3c9ff8 to your computer and use it in GitHub Desktop.
Save zahra-ove/d35c17fc031a25a8d873dcd5cd3c9ff8 to your computer and use it in GitHub Desktop.

resource which I must study continously and carefully:

  1. https://www.php.net/manual/en/langref.php
  2. https://github.com/phpinternalsbook/PHP-Internals-Book
  3. https://www.npopov.com/2015/06/19/Internal-value-representation-in-PHP-7-part-2.html
  4. https://phpsecurity.readthedocs.io/en/latest/index.html



PHPStorm notes:

  1. how zoom all the IDE?
    • press ctrl + backtick
    • select zoom

important notes in PHP:

  1. new feature added in php 8.0 called constructor property promotion.
  2. VO: value object
  3. DTO: data transfer object
  4. in php it is not possible to typ hint properties with callable type.
  5. The object operator, ->, is used in object scope to access methods and properties of an object.
  6. Null-safe operator is a new syntax in PHP 8.0, that provides optional chaining feature to PHP. e.g. $foo?->bar?->baz;
  7. isset() => Determine if a variable is declared and is different than null.
  8. Null coalescing operator => The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not null; otherwise it returns its second operand.

note: null coalescing operator does not work on methods. what does it mean?

$transction = new Transction;
$transction->getCustomer()->getProfiler()->id ?? 'something1';

the above code does not work properly becuase null coalescing operator does not work on methods. the right way to write above code is to use nullsafe operator.

    $transction = new Transction;
    $transction->getCustomer()?->getProfiler()?->id ?? 'something1';
  1. importing classes in php is per file, which means if in file A we have some use statement to import other classes and also in this file we have include statement to include file B, then imported classes in file A is not availabe in file B.

  2. a final class in php can not be extended.

  3. a final method in a class in php can not be overwritten by child class.

*** final keyword is used to prevent class extension and method override.

  1. a child class just can increase visibility of public and protected properties of parent class but can not decrease the visibility of those properties.

example:

class A {
  protected a;
}

class B extends A {
  public a;
}
  1. php does not allow multiple inheritance but it supports multi level inhertance which cause hierarchal inheritance.

  2. child class can not access to private properties and methods of parent class => so it can not override private and protected proprties and methods of parent class.

  3. in php, interface could not have any property but it could have constant.

note: the constant which is defined in an interface could not be overridden with other classes who implemented target interface.

  1. magic method __get() is called when trying to access a non-exsiting or inaccessible property in an object.

  2. magic method __set() is called whenever trying to assign a value for a non-exsiting or inaccessible property in an object.

  3. magic method __call() is called whenever a non existing or inaccessible method get called on target object.

  4. magic method __callStatic is called when a static method on a class is called and that method does not exists.

  5. for implementing single action classes, a method called __invoke must be declared in the class. so by default objects are not callable, but if a class has __invoke method, then the object from that class is callable. (session 46 Programming with Gio)

  6. __debugInfo is called whenever trying to var_dump the object. in __debugInfo method we could specify which properties of object is allowed to be printed. becuase in defult mode, when printing an object; all of its private properties also get printed.

  7. in oop, this keyword refers to "calling object". 24.in oop, self refers to where the method is defined, and not where the method is called. in here where means which class.

$this resolve the class at run time. self resolve the class at compile time.

###note: so there is a concept named: early binding and late binding.

  1. there is two types of binding.

early binding which happens at => compile time and late bindind which happens at => run time.

  1. $this => late binding => considers current calling object
  2. self => early binding => considers in which class the calling method locate and consider that class.
  3. static keyword is called in run time so it is late binding. static considers the method is called in which class, and not is defined in which class.

note: seld keyword resolves the class at compile time. this is the limitation of self keyword.

  1. spl_object_id() which returns the object identifier.

  2. php does not support multiple inheritance, but we can implement multiple inheritance by using traits and interfaces in php.

  3. in php traits precendece in important. suppose there is a parent class called parentClass and a child class called childClass and a trait called sampleTrait.
    if there is a common method in childClass and in the trait, the the method in childClass is considered.
    if there is a common method in parentClass and in trait, then the method in trait is considered.

  trait sampleTrait {
    public function method2() {
      //
    }
  }
  
  class parentClass {
  
    public function method1() {
      //
    }
  }
  
  class childClass extends parenrClass {
      use sampleTrait;
         
  }
  1. in php trait. there might be a conflict between traits methods. suppose we have a class called classA and this class uses two different traits:
trait TraitA {

    public function method1()
    {
        echo "method1 from " . static::class . PHP_EOL;
    }
}

trait TraitB
{
    public function method1()
    {
        echo "method1 from " . static::class . PHP_EOL;
    }
}

to solve the conflict problem, we must determine that method1 from which trait should be considered. also we could rename method1 for each trait by definig an alias to it.

class ClassA
{
    use TraitA {
        TraitA::method1 insteadof TraitB;
    }
    use TraitB {
        TraitB::method1 as originalMethod1;
    }
}
require_once dirname(__DIR__) . '/app/traitA.php';
require_once dirname(__DIR__) . '/app/TraitB.php';
require_once dirname(__DIR__) . '/app/ClassA.php';

$classa = new ClassA();
$classa->method1();
$classa->originalMethod1();
  1. it is possible to change visibility of a trait's method in target class. suppose we have a class called classA which uses a trait named TraitA like this:
trait TraitA {

    private function method1()
    {
        echo "method1 from " . static::class . PHP_EOL;
    }
}


class ClassA
{
    use TraitA{
        TraitA::method1 as public;
    }
}

and then:

$classa = new ClassA();
$classa->method1();
  1. if a property is defined in a trait, then the underlying class can not have the same property unless it would be fully compatible, which means "visiblity level", "data type", and "initial value" should be the same.

  2. important note: 😊 =? trait could have abstract method! (Programming with Gio/Lesson 48) ==> be it is not a good idea to have abstract method in a trait. because abstract method is some how some type of contract, and contract is better implemeted by abstract class or better interface. trait is jut for simple code reuse.

  3. we all know in a abstract class, all methods could be public or protected. in other words, it is not possible to define an abstract method as private method. but please not since php 8, it is possible to define an abstract method in a trait as private. please note this is olny possible for traits. (Programming with Gio/Lesson 48)

  4. important note: if a parent class has a static property, then this static property is shared among all child classes, this means if any one of child classes changed the parent class static property, then this static property got change in all places. because it is shared. BUT in traits this is not true. if TraitA is used in both classA and classB; then if TraitA has a static property, this property is not shared among other classes and each class which uses traitA has its own static property. (Programming with Gio/Lesson 48)

  5. magic constant __CLASS__ => if this magic constant is used in a trait, then it points to a class which uses the trait.

  6. traits => are for code reuse

  7. interfaces => are for contract

  8. another important rule which could be considered is that if in a base class a method is defined as final, then this method can not be overriden in derived classes. BUT this rule is not true in trait. in a trait if any method defined as final, then the class which uses the trait can redefine that method/

  9. note: trait allows non related and also independent classes share common functionality.

Gio(session 50):
42. === => identity operator / strict equality operator
== => comparison operator/ equal operator

  1. in comparing two objects by == : the two objects are equal if both are instance of same class and have same properties with same value.

  2. in comparing two objects by ===: the two objects are equal if both of them point or refer to the same instance of the same class.

  3. PHP already has support for void type. It is only allowed as a return type because using void anywhere else wouldn't make any sense.
    In PHP 8.0 Union Types, the void type is not allowed to be combined with any other type.

  4. for copying an object, we can clone that object like this:\

  $obj1 = new sampleClass();
  $obj2 = clone $obj1;

note: when cloning an object, the constructor method does not get called when cloning the object.
when cloning an object, a method called __clone get called.

  1. cloning an object is considered as shallow copy but serializing/deserializing an object is considered as deep copy.

  2. Serializable interface is deprecated in php 8.1 and will be removed in php 9.\

  3. there are four magic methods related to serialization: __sleep , __wakeup , __serialize , __unserialize.

  4. __sleep is called before serialization start. __wakeup method is called after desialization.

  5. if unserialization process failed, then unserialize function returns false and also generate notice error.

  6. __serialize magic method is just like __sleep magic method. both of them are called before serializing the object. but the difference is that ==> in __serialize method we could specify which properties of the object must be in seialize process and if any change on any property is needed before serialization process it is possible to define these changes in __serialize method. but on the other hand for __sleep method it is possible to just define which properties of object must be serialize and it is not possible to define any change which is needed to be taken before serialization. also note that __serialize method has precendence over __sleep method.

  7. there is __wakeup and __unserialize method. they work just like above notes mentioned but in reverse manner. both methods are called after deserializing the object. __unserialize method has more precedence than __wakeup method.

  8. exception handling is the OOP way of error handling.

  9. in europe date format is: day-month-year

  10. in U.S. date format is: month/day/year

  11. in php if date format is seperated by / ==> php by default consider it as U.S. date format by id date is seperated by . or -, then php consider it as european date format.

  12. output_buffering directive is always off in PHP-CLI.

  13. php has variable variable and also variable functions. e.g.:

$func = "sqrt";
print $func(49);

As variable functions are quite unusual and also easy to get wrong, there is a special PHP function, is_callable(), that takes a string as its only parameter and returns true if that string contains a function name that can be called using a variable function. Thus, our script becomes this: (source: http://www.hackingwithphp.com/)

  $func = "sqrt";
  if (is_callable($func)) {
      print $func(49);
  }

As an alternative to variable functions, you can use call_user_func() and call_user_func_array(), which take the function to call as their first parameter. The difference between the two is that call_user_func() takes the parameters to pass into the variable function as multiple parameters to itself, whereas call_user_func_array() takes an array of parameters as its second parameter.

This next script demonstrates both of these two performing a functionally similar operation, replacing "monkeys" with "giraffes" in a sentence using str_replace(): (source: http://www.hackingwithphp.com/)

  $func = "str_replace";
  $output_single = call_user_func($func, "monkeys", "giraffes", "Hundreds and thousands of monkeys\n");
  $params = array("monkeys", "giraffes", "Hundreds and thousands of monkeys\n");
  $output_array = call_user_func_array($func, $params);
  echo $output_single;
  echo $output_array;
  1. Covariance
    covariance allows a child's method to return a more specific type than the return type of its parent's method.

  2. Contravariance
    contravariance allows a parameter type to be less specific in a child method, than that of its parent.

  3. PHP supports:

    • covariant return type
    • contravariant parameter type
  4. single quotes ('') vs double quotes (""):
    In PHP, single quotes ('') are generally faster than double quotes ("") because with single quotes, PHP does not evaluate the contents for variables or special characters, whereas with double quotes, PHP performs variable interpolation and evaluates escape sequences.

When you use double quotes, PHP needs to scan the string for variables and special characters to replace them with their values, which adds a slight overhead compared to single quotes where no such processing is needed.

However, the performance difference between single and double quotes is usually negligible unless you're dealing with a massive number of string manipulations or in a very performance-critical application. In most cases, the readability and convenience of using double quotes outweigh any minor performance considerations.

  1. when using try-catch block, if it is needed to use multiple exceptions, it is possible to use bit wise or operator. the sample code is:\
try {
    ... throws ReflectiveOperationException ...
}
catch (ClassNotFoundException | IllegalAccessException ex) {
    ... body ...
}
  1. there is two way for comparing two objects in php:\
  • loos comparison
  • strict comparison

in loos comparison --> it just compares object property values
in strict comparison --> compares object identities\

  1. when making any change in autoload section of composer.json file, then it is needed to composer dump-autoload or composer du.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment