DEV Community

StuartCreed
StuartCreed

Posted on • Updated on

PHP Basics

Declaration
<?php
All php files must start with the above.
They do not need to be closed with ?> (although some people prefer to), it makes no difference to the interpreter. Skipping the closing tag avoids accidentally printing whitespace in your page from your code-only files.

Tools
Packagist -> A website which allows you to search publicly available PHP composer packages.

Composer -> Like npm (in the javascript world), but for PHP.

Operators
-> allows you to access PHP object properties and is like the . in JavaScript.
=> is used in arrays:

$myArray = array(
0 => 'Big',
1 => 'Small',
2 => 'Up',
3 => 'Down'
);

; must go after every PHP statement!

Name Space

namespace App;
use Jsjdjjd\Model;

namespace means that you can use the same variable names twice in an app as the space in which it is declared is labelled. You can use the “use” command to extract a certain PHP class from a different namespace

Classes
They can include methods (functions) and properties
https://www.w3schools.com/php/php_oop_classes_objects.asp
e.g.

<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Constructor
  function __construct($color) {
     $this->color = $color;
  }

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
?>
Enter fullscreen mode Exit fullscreen mode

:: allows you to access a PHP class Method or property

use PATHNAME\CLASSNAME; /*this can utilise a class from a different directory*/
CLASSNAME::staticmethod(); //How you would access a static method of that class.

Function types:
public - the property or method can be accessed from everywhere. This is default. i.e. function === public function
protected - the property or method can be accessed within the class and by classes derived from that class
private - the property or method can ONLY be accessed within the class

How to write a static function:

static function () {
}

Top comments (0)