Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP class: assigning static property via constructor

Tags:

php

class

Simplified example of a class:

class Table extends TableAbstract{
    protected static $tablename;

    function __construct($str){
       $this->tablename = "table_" . $str;
       $this->insert();    // abstract function
    }

}

When I've used classes like this in the past I've assigned the $tablename directly when writing the class. This time however I would like it to be decided by the constructor. But when I then call the function referencing $tablename the variable seems to be empty, when I echo the SQL.

What am I doing wrong, or could someone suggest a way to achieve what I want here?

Thanks for any comments/answers..

like image 745
grai Avatar asked Jun 24 '11 22:06

grai


People also ask

Can static class have constructor in PHP?

A static constructor is just a method the developer can define on a class which can be used to initialise any static properties, or to perform any actions that only need to be performed only once for the given class. The method is only called once as the class is needed.

Why we use static methods in PHP?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.

Why do we use static methods?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

What is the difference between using self and this?

The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.


1 Answers

As the property is static, access it using Table::$tablename - or alternatively self::$tablename to refer implicitly to the current class.

like image 169
Alexander Gessler Avatar answered Nov 03 '22 00:11

Alexander Gessler