Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Not a member yet? Click here to register.
Forgot Password?

The Upcoming of PHP-8

Asked Modified Viewed 1,527 times
C
Chan
C
Chan 0
Lead Developer of PHP-Fusion
  • Super Admin, joined since
  • Contributed 3,841 posts on the community forums.
  • Started 232 threads in the forums
  • Started this discussions
  • Answered 6 questions
asked
Super Admin

The PHP 8, is a new major PHP version and will be expected to be released on [url="https://wiki.php.net/todo/php80"]December 3,2020.[/url] It is currently in development still, and things are much likely to change a lot still in the following months to come.

In order to avoid your code breaking, we've compiled a list of enhancements the PHP developers did, and what will be deprecated in before the 7 versions go obsolete.

The good news, during Earth keep rotating and people are at the liberty of making such shift beyond our control and breaking our current codes, they also managed to come up with the new features
such as the JIT compiler, union types and more.

So lets get going with the good news first.

What is JIT compiler?

A JIT, short abbreviation for Just in Time compiler is a performance. We will not go into detail here, but you can read them up if you want to know and what is going on there.
Our summary is, objects and classes have been optimized for lesser garbage collection and it can improve your site speed by at least a whopping 53%, but it is still now
unsure how PHP 8 will impact the speed of web request headers yet, but we are sure someone will start benchmarking them after this.

PHPFusion has been always lightweight fast when it comes to rendering. According to our latest test carried out by RobiNNN using devilbox docker container the following were carried out:

Test score benchmark running on:

PHPFusion 9.0.5x with all core infusions installed, Default Magazine theme.
[ulist=disc]Speed score on PHP 7.4 - 0.12s. (with cache going, recording a 0.05s at some page refresh)[/ulist]
[ulist=disc]Speed score on PHP 8.0 - 0.07s. (With cache going, recording a 0.02s at some page refresh)[/ulist]

What is new in PHP-8?

Static return types were spatially valid (or wasn't a valid return type) until approved in PHP 8.
class Foo
{
 public function test(): static
 {
 return new static();
 }
}



New str_contains() function

Instead of doing this:
if (strpos('string with lots of words', 'words') !== false) { /* … */ }

You can now do this in PHP 8:
if (str_contains('string with lots of words', 'words')) { /* … */ }

New str_starts_with() and str_ends_with() function
str_starts_with('haystack', 'hay'); // true
str_ends_with('haystack', 'stack'); // true

New fdiv() function
The new fdiv() function does something similar as the fmod() and intdiv() functions, which allows for division by 0.
Instead of errors you'll get
INF
,
-INF
or
NAN
, depending on the case.

Ternary Statement just got Cleaner.[big]
Now, this is what is we have been doing.

$some_array = array("one" => 1, "two" => 2);

$one = !empty($some_array["one"]) ? $some_array("one") : ""; // returns 1
$one = isset($some_array["one"]) ? $some_array("one") : ""; // returns 1
$one = $some_array["one"] ?: ""; // returns 1, skipping empty or isset checks and might risk undefined offset notices


In PHP 8, you can do this:
$one = $some_array["one"] ?? empty; // returns 1 with isset checks.


PHP 8 will allow you to simplify all checking whether a key is in an array by introducing the new coaelescing operator, "?" symbol.
Returning a value after checking a key is in an array definitely will come very handy for all of us. It's also a much cleaner approach.

[big]New Invoke Method in Class.

class Example {

   public function __invoke() {
    echo "Hi there";
   }

   public function php7_print() {
    echo "Hi there";
   }

}

$example = new Example(); // returns Hello world


By adding the invoke method within our class, we can use an instance of it as if it were a function.
You can now define Event Listeners whenever using a class which previously unavailable without calling a particular method such as php7_print.

New Traits
Traits are replacements to same methods within different classes, or what-i-usually-call a utility class. Let me explain it better. There are often times where
you face a situation where you need to run the same piece of code within several classes. In the following example, I'll be doing 2 classes, one which I use for
the directory page, and one for the home page. The similarity here is that I have an item which requires to run a format function which must be identical.
class Directory {
   private $value;

   public function process($string) {
      // sanitizes the string and set class variable
      $this->value = stripinput($string);

      return $this->format();
   }

   public function format($value) {
      if ($this->value) {
       return 'Now $'.number_format($value, 2);
      }
      return "";      
   }
}

class FrontPage {

   private $value;

   public function process($string) {
      // sanitizes the string and set class variable
      $this->value = stripinput($string);

      return $this->format();
   }

   public function format() {
      if ($this->value) {
       return 'Now $'.number_format($this->value, 2);
      }
      return "";      
   }
}


There are ways that we can do this without duplicating the format function in both classes such as extending the class with another class or create a non object oriented function,
but we're not going to examine them here but to show what PHP 8 can do.

To continue with PHP 8, traits works as such ways that the format method can be grouped and shared between both classes.
trait Formatter {

   private $value;

   private function format() {
      if ($this->value) {
       return 'Now $'.number_format($this->value, 2);
      }
      return "";      
   }
}

class FrontPage {

   use Formatter;
   
   public function process($string) {
      // sanitizes the string and set class variable
      $this->value = stripinput($string);

      return $this->format();
   }
}

class Directory {

   use Formatter;

   public function process($string) {
      // sanitizes the string and set class variable
      $this->value = stripinput($string);

      return $this->format();
   }
   
}

Notice that in using trait, the method remains as private methods as oppose to if you are using a non object oriented method or extending a class which such callables properties must be public.

Access array within an array without need to extract them through their key and position.
Assume we have a group of users.
$users = array(
   array(1, "Super Administrator"),
   array(2, "Administrator"),
   //...
);


previously on PHP 7, to assign the id and level, we could have need to do something like this.

// PHPFusion function to flatten nested array
$users = flatten_aray($users);
foreach($users as $user_array) {
   $user_id = $users[0]; // here we need to know the index/position 0 is id
   $user_level = $users[1]; // here we need to know the index/position 1 is level
}


But on PHP 8, you can directly assign them as such

foreach ($people as array($id, $user_level)) {
   // do something
}


Extending try catch with finally statement
If a method or function throws an exception, you might want to extract the error, but when an exception happens, you might want to carry out a task regardless of the execution flow that has been followed.
try {
   // run input sanitization. And it might throw and exception for unsupported module.
   $sanitize_input = sanitizer("post_1", "", "post_1") ?? : "";
} catch (\Exception $e) {
   echo $e->getMessage();
} finally {
   // Always make sure that we can do something here
}

New Arrow Functions
With array_map, array_filter, and array_reduce, you could have done such currently
$calculate_cube = function calculate_cube($n) {
 return ($n * $n * $n);
}

$cube = array_map('calculate_cube', array(1, 2, 3, 4, 5));

$cube = array_map($calculate_cube, array(1, 2, 3, 4, 5));

$cube = array_map(function($n) {
 return ($n * $n * $n);
}, array(1, 2, 3, 4, 5));


But in PHP 8, you can also do this in no time by using the "arrow => functions".
$cube = array_map(fn($n) => $n * $n * $n, array(1, 2, 3, 4, 5));

Invoke methods and functions previously only by using a Reflection class. A reflection class is a common utility function that allows us to set objects and methods without actually running it in your script.
A way to explain it is as such:
/** We want to use the Defender class */
$class_name = "PHPFusion\\Defender";
/** We want to run the sanitizer function */
$method_name = "sanitizer";
/** Parameter for sanitizer function, the input name being posted */
$input_name = "settings"; // for $_POST["settings"]

$object = new ReflectionClass($class_name);
$class = $object->newInstance();
$method = array($class, $method_name);
if (is_callable($method)) {
 /** Dynamically it will call the assigned function of the assigned object and assign parameters */
 $value = call_user_func($method, $raw_value, "", $input_name);
}

// Basically, it is equivalent to
$value = santizer($input_name, "", $input_name);

But in real application case, what I will do is to function it as such to have a utility or purpose.
/** Universal class / method loader **/
function reflect($class_name, $method_name, $param) {   
   $object = new ReflectionClass($class_name);
   $class = $object->newInstance();
   $method = array($class, $method_name);
   if (is_callable($method)) {
       /** Dynamically it will call the assigned function of the assigned object and assign parameters */
    $value = call_user_func($method, $param);
   }
}


And as such, without replicating your code, you can run any class/method you want with your parameter without actually calling the class.
Imagine this application in our display controller. Here we are not calling any class, any method but by depending on the situation given, to reflect the method.
As such, there are nothing to debug at least on this function itself if something is wrong. We save 1 file less to debug, and more into automating stuff.
function view_forum() {
   if ($_GET["view"] == "thread" && isnum($_GET["thread_id"])) {
   // I want to view a thread
      return reflect("PHPFusion\\Infusions\\Forum\\Threads", "view", $_GET["thread_id"]); // returns a parsed thread HTML
   } elseif ($_GET["viewforum"] === true && isnum($_GET['forum_id"])) {
      return reflect("PHPFusion\\Infusions\\Forum\\Forums", "view", $_GET["forum_id"]); // returns a parsed thread HTML
   } else {
      ...
   }
}


The second reason we use such method invocation is for dynamic variety capability of the PSR-4 loaders that does not require us to include dependencies files and thus saves a heck lot of time managing file requires and method exists checks.

But if you would want to include every single file in the entire project into the very same page, that is another theory we can discuss later on.

So looking at the above code, how does PHP 8 one looks like?

First, we have our class like so:
class Defender {

    /** This is very minimal, the actual function in PHPFusion is a behemoth in cleaning user inputs */
    public function santizer($input_name, $default, $input_name) {
      // just an example of simple return
      if ($input_name) {
         $value = stripinput($input_name); // basic add slashes
         $value = descript($value); // clean up the code against malicious scripts
         $value = censor_words($value); // run a bad words censor
      }
      return $default;
   }

}

The invoke method is to do something like this by right.
$method = 'sanitizer';
$parameter = 'settings';
$object = new Defender();
echo $object->$method($parameter, "", $parameter);


Which can be done in such a way through your own custom invoker class
class ExampleInvoker {

   public function invoke($object, string $method, $parameter) {
      return $object->$method($parameter, "", $parameter);
   }

}

$a = new Defender();
$b = new ExampleInvoker();
$b->invoke($a, 'sanitizer', 'settings);


[/b]Now the bad news..[/b]
What is being deprecated? No, not much really. If you would like to know more, here is a list of the deprecations that had been now finalized in PHP 8.

<a href="https://wiki.php.net/rfc/deprecations_php_7_2">Deprecated in 7.2</a>
<a href="https://wiki.php.net/rfc/deprecations_php_7_3">Deprecated in 7.3</a>
<a href="https://wiki.php.net/rfc/deprecations_php_7_4">Deprecated in 7.4</a>


[/b]Others: Reclasffied engine warnings[/b]
Undefined variable: Error exception instead of notice
Undefined array index: warning instead of notice
Division by zero: DivisionByZeroError exception instead of warning
Attempt to increment/decrement property '%s' of non-object: Error exception instead of warning
Attempt to modify property '%s' of non-object: Error exception instead of warning
Attempt to assign property '%s' of non-object: Error exception instead of warning
Creating default object from empty value: Error exception instead of warning
Trying to get property '%s' of non-object: warning instead of notice
Undefined property: %s::$%s: warning instead of notice
Cannot add element to the array as the next element is already occupied: Error exception instead of warning
Cannot unset offset in a non-array variable: Error exception instead of warning
Cannot use a scalar value as an array: Error exception instead of warning
Only arrays and Traversables can be unpacked: TypeError exception instead of warning
Invalid argument supplied for foreach(): TypeError exception instead of warning
Illegal offset type: TypeError exception instead of warning
Illegal offset type in isset or empty: TypeError exception instead of warning
Illegal offset type in unset: TypeError exception instead of warning
Array to string conversion: warning instead of notice
Resource ID#%d used as offset, casting to integer (%d): warning instead of notice
String offset cast occurred: warning instead of notice
Uninitialized string offset: %d: warning instead of notice
Cannot assign an empty string to a string offset: Error exception instead of warning
Supplied resource is not a valid stream resource: TypeError exception instead of warning


I hope that this article will be able to inspire you or help you to continue improvising your codes as developers.

Thank you.
0 replies
There are no post found.

Category Forum

General Discussion

Labels

None yet

Statistics

  • Views 0 views
  • Posts 0 posts
  • Votes 0 votes
  • Topic users 1 member

1 participant

C
C
Chan 0
Lead Developer of PHP-Fusion
  • Super Admin, joined since
  • Contributed 3,841 posts on the community forums.
  • Started 232 threads in the forums
  • Started this discussions
  • Answered 6 questions

Notifications

Track thread

You are not receiving notifications from this thread.

Related Questions

Not yet