Static vs Non-static methods in PHP. what is faster?

As you know there are two types of methods in PHP classes: static and non-static. To be called a non-static method needs an instance of its class, and static method can be called without instantiating of the class. 

In the meantime there are two very common questions:

  • When to use non-static methods and when to use static methods?
  • Is there any performance difference between static and non-static methods?

These are very common dilemmas among PHP developers. Most of developers guess that static methods must work faster because there is no object instance with all its properties involved to the call. Sounds logical. Is that actually true?

As I already mentioned above, and as you already know, the main difference between static and non-static methods is that static methods do not need an instance of the class to be called in the code. It means that for static methods there is no need to create object and keep in the memory. So, at least we can save some memory which can also affect the performance

Some experiments

To test the performance of static and nonstatic methods let’s create two similar classes. The only difference will be how we call methods in the class.

 

Static class

<?php
set_time_limit(0);
Class Static0 {

	public static $counter = 0;
	
	public static function incrByTwo()
	{
		self::$counter = self::$counter + 2;
	}
}

Class Static1 extends Static0 {

	public static function incrByOne()
	{
		self::$counter = self::$counter + 1;
	}
	
	public static function incrByTwo()
	{
		parent::incrByTwo();
	}
}

$time_start = microtime(true);
for($i=0;$i<100000;$i++) {
	Static1::incrByOne();
	Static1::incrByTwo();
}

echo Static0::$counter ;
$time_end = microtime(true);
$time1 = $time_end - $time_start;
?>
Total execution time is <?php echo $time1;?>
Used memory: <?php echo memory_get_usage();?>

NonStatic class

<?php
set_time_limit(0);

Class Static0 {

	public $counter = 0;

	public function incrByTwo()
	{
		$this->counter = $this->counter + 2;
	}
}

Class Static1 extends Static0 {
	
	public function incrByOne()
	{
		$this->counter = $this->counter + 1;
	}
	
	public function incrByTwo()
	{
		parent::incrByTwo();
	}
}

$time_start = microtime(true);
$obj = new Static1();
for($i=0;$i<100000;$i++) {
	$obj->incrByOne();
	$obj->incrByTwo();
}

echo $obj->counter ;

$time_end = microtime(true);
$time1 = $time_end - $time_start;
?>

Total execution time is <?php echo $time1;?>
Used memory: <?php echo memory_get_usage();?>

Okay, now we know that static methods are indeed generally faster than non-static methods. And the difference in memory consumption doesn’t look significant at all…

So, use static methods everywhere now?

Not really. Short answer to this question would be: you don’t need an object and don’t need a non-static method if the method doesn’t interact with properties or methods in the class and its parents/children.

Yes, static methods look  faster. In the meantime, a lot of developers believe (and they have good reasons) that using static methods and properties break a lot of the power available to Object-Oriented code. They also mention that Unit testing is impossible using static methods.

Insert data from CSV file in PHP with PDO

<?php

// Database Connection
$hostname = "localhost";
$username = "root";
$password = "mf2312";

try {
    $db = new PDO("mysql:host=$servername;dbname=csvtest", $username, $password);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}




// Create  CSV to Array function

function csvToArray($filename = '', $delimiter = ',')
{
    if (!file_exists($filename) || !is_readable($filename)) {
        return false;
    }

    $header = NULL;
    $result = array();
    if (($handle = fopen($filename, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
            if (!$header)
                $header = $row;
            else

                $result[] = array_combine($header, $row);
        }
        fclose($handle);
    }


    return $result;
}




// Insert data into database   

    $all_data = csvToArray('files/testcsv.csv');
    foreach ($all_data as $data) {

        $sql = $db->prepare("INSERT INTO students (name, roll, department) 
        VALUES (:name, :roll, :department)");
        $sql->bindParam(':name', $data['name']);
        $sql->bindParam(':roll', $data['roll']);
        $sql->bindParam(':department', $data['department']);
        $sql->execute();

    }

What I learned from my team in the beginning of my job.

I think that as a beginning  label  the most important it is to work  with a team.

When you work individually  you don’t know what you don’t know.  But when you join a team,  your senior  people and your team leader  find out your weak point and they are help  you in proper way  to improve your skill. You don’t know what the senior people know- no matter how good you think you are. It is good to exposure to both the best and the worst of what other people do. You can learn from both.

After learning programming and software development  a beginner  can write code and build project. But  in individual time period  he does not know how to write code in organized way  but if  he does work with a team he can learn from  senior people and team leader how to write aswame code.

We can learn lots of thing  from a team  such as team management system, group working, new technologies, new ideas etc.

What is HTTP? And what is the difference between GET and POST?

In this  article  we will be  discussing  about HTTP protocol. HTTP is the foundation of data communication for the world wide web. HTTP  stands for “Hyper Text Transfer Protocol”. It was implemented first by Tim Berners-Lee at CERN in 1990.The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.

A web browser using which a request is initiated is called as a client and a web server which respond’s to that request is called as a server.

 

http

 

GET

  • Parameters remain in browser history because they are part of the URL.
  • The GET method is restricted to send upto 1024 characters only.
  • GET can’t be used to send binary data, like images or word documents, to the server.
  • GET method should not be used when sending passwords or other sensitive information.
  • The data sent by GET method can be accessed using QUERY_STRING environment variable.
  • Can be bookmarked.
  • The PHP provides $_GET associative array to access all the sent information using GET method.

POST

  • Parameters are not saved in browser history.
  • The POST method does not have any restriction on data size to be sent.
  • The POST method can be used to send ASCII as well as binary data.
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
  • Can not be bookmarked.
  • The PHP provides $_POST associative array to access all the sent information using POST method.

Simple pagination in PHP

This is a simple PHP pagination script. First create a database and create a table name users  then connect your database by hostname, username, password, dbname to run this script. you can change table name and add more column.

<?php

$conn = new mysqli('hostname', 'user', 'password', 'dbname');
$start = 0;
$limit = 10;

if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $start = ($id - 1) * $limit;
} else {
    $id = 1;
}
$sql = "SELECT * FROM users LIMIT $start, $limit";
$query = $conn->query($sql);
?>

<html>
<head></head>
<body>
    <table>
        <tr>
            <th>Name</th>
            <th>department</th>
        </tr>
        <?php
        while ($result = mysqli_fetch_array($query)) { ?>
        <tr>
            <td><?= $result['name'] ?></td>
            <td><?= $result['department'] ?></td>
        </tr>
        <?php } ?>

    </table>
    <?php
    $rows = mysqli_num_rows(mysqli_query($dbconfig, "select * from user"));
    $total = ceil($rows / $limit);
    if ($id > 1) {
        echo "<a href='?id=" . ($id - 1) . "' class='button'>PREVIOUS</a>". "      ";
    }
    if ($id != $total) {
        echo "<a href='?id=" . ($id + 1) . "' class='button'>NEXT</a>";
    }
    ?>
    <ul class='page'>
        <?php
        for ($i = 1; $i <= $total; $i++) {
            if ($i == $id) {
                echo "<li class='current'>" . $i . "</li>";
            } else {
                echo "<li><a href='?id=" . $i . "'>" . $i . "</a></li>";
            }
        }
        ?>
    </ul>
</body>
</html>