PHP class constructors and methods - php

I just started learning PHP and I am having trouble with its syntax. I am learning how to write a class in php, and I used a syntax kinda similar to Java. However, I can get neither its constructor nor regular method to work and I can't figure out why.
<?php
class bento {
public $food;
public $staple = "rice";
protected $veggie = "kale";
public function __construct($fd){
$food = $fd;
}
public function getstaple(){
return $staple;
}
}
$chicken=new bento("chick");
echo "<br>".$chicken->food;
echo "<br>".$chicken->staple;
$fd=$chicken->getstaple();
echo "<br>".$fd;
echo "<br>".$chicken->getstaple();
?>
Here is the result that I have got:
//result
rice
//end of result
Basically, out of 4 lines, I only got one line to work (print out the $staple variable). The constructor did not assign "chick" value to $food. The getstaple() function did not return any value.
I can't figure out how to get this to work.

To refer to a class member, you should use $this->food or $this->staple
class bento {
public $food;
public $staple = "rice";
protected $veggie = "kale";
public function __construct($fd){
$this->food = $fd;
}
public function getstaple(){
return $this->staple;
}
}

The same in java, you need to access your class variables using the "this" keyword. In php, you would do something like:
$this->methodName();
or
$this->variableName

In PHP all variables are local to the scope they are defined within (with a few language provided exceptions like the superglobals $_GET, $_POST, $REQUEST, $_SERVER etc..)
This means that when you reference $food within your method your are referring to $food as it is defined within that method in other words a function variable as opposed to the instance property that you intended.
For instance methods PHP is nice enough to create for you a reference to the instance that a method was called on called $this This allows for you to reference properties and methods of an object from within the object itself via this format.
$this->food = $fd
Another thing to note is class methods and properties are not accessible this way. They require the use of the scope resolution operator :: so to get at a staticly defined class property or method you would use:
ClassName::method();
or
ClassName::$property;
As with $this php provides some easy access to the class properties via the self and static keywords.
self is a reference to the class that a static method was defined on.
static is a reference to the class that the static method was called on.
To illustrate the difference see this code
class A {
static public $toWho = "Class A";
static public function sayHelloSelf(){
echo "Hello ".self::$toWho;
}
static public function sayHelloStatic(){
eecho "Hello ".static::$toWho;
}
}
class B extends A {
static public $toWho = "Class B";
}
B::sayHelloSelf(); // echos Hello Class A
B::sayHelloStatic(); // echos Hello Class B

this keyword is used to access the class member within the current class.
You create class you have assign some value for variable $food.
then within the function you have tried to access the variable but $food is class variable we cannot access the class members without object or scope resolution operator.
"this" has current object name .

Related

Trying to access data from one class inside a other class

Trying to get some data from one method in side static method(using it inside a other class) but I get the 'Using $this when not in object context in...' error.
Below a basic example
class mClass{
public $someVar = 'Hello world...';
public function passFunc(){
$give = $this->someVar;
return $give;
}
public static function showFunc(){
$show = self::passFunc();
return $show;
}
}
mClass::showFunc();// show error: Using $this when not in object context in...
You can't use $this, when you are working with static variables. $this is a pointer to the current object, but static variables belongs to class.
A class method (or static function) isn't tied to a particular instance of your class, i.e. it doesn't have $this although self is available.
A class method can access static properties or methods, but accessing anything else within the class will raise an error. It's best to look at static methods as a means to organize functions; as such, they operate in between external functions and instance methods.
In your case, you'd have to create an instance inside your static method:
public static function showFunc()
{
$o = new self;
$show = $o->passFunc();
return $show;
}

PHP OOP - constant vs static variables?

In PHP, What is is the difference between:
Constants and static variables?
Extending a class and creating its object?
I know how they can be used, but I can't clearly distinguish between them.
Comparison
Static
Can has a access modifier.
class A{
public static $public_static = "can access from anywhere";
protected static $protected_static = "can access from inheriting classes";
private static $private_static = "can access only inside the class";
}
Depending the visibility you can access static variables.
//inside the class
self::$variable_name;
static::$variable_name;
//outside the class
class_name::$variable_name;
Can change the value after declaration.
self::$variable_name = "New Value";
static::$variable_name = "New Value";
No need to initialize when declare.
public static $variable_name;
Normal variable declaration rules applied(ex: begins with $)
Can create inside a function.
class A{
function my_function(){
static $val = 12;
echo ++$val; //13
}
}
Constant
Always public cannot put access modifiers(>PHP7.1)
class A{
const my_constant = "constant value";
public const wrong_constant="wrong" // produce a parse error
}
Anywhere you can access constant.
//inside the class
self::variable_name;
static::variable_name;
//outside the class
class_name::variable_name;
Cannot change the value after declaration.
self::variable_name = "cannot change"; //produce a parse error
Must initialize when declare.
class A{
const my_constant = "constant value";// Fine
const wrong_constant;// produce a parse error
}
Must not use $ in the beginning of the variable(Other variable rules applied).
class A{
const my_constant = "constant value";// Fine
const $wrong_constant="wrong";// produce a parse error
}
Cannot declare inside a function.
When Extending
class A{
public static $public_static = "can access from anywhere";
protected static $protected_static = "can access from inheriting classes";
private static $private_static = "can access only inside the class";
const my_constant = "Constant value";
}
class B extends A{
function output(){
// you can use self or static
echo self::$public_static; //can access from anywhere;
echo self::$protected_static; //can access from inheriting classes;
self::$protected_static = "Changed value from Class B";
echo self::$protected_static; //"Changed value from Class B";
echo self::$private_static; //Produce Fatal Error
echo self::my_constant;//Constant value
}
}
Static is for:
class properties or methods as static makes them accessible without needing an instantiation of the class
So, the value returned by a static member may differ. For example, you can call a static method with different result depending of what parameters you pass to it.
Constants value:
must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
So, it always return the same result when you call it
About create an object and extending a class, when you "create an object" you make an instance of a class. When you extend a class, you create an other class who:
inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
I hope it help you.
A constant is constant and can NOT change its value once assigned. A static variable, on the other hand, can have varying values. For example, you can create a static variable inside a function to know how many time the function was called. The value will change each time function is called eg if you do $i++ where $i is static variable.
As for extending a class and creating its object, this is known as inheritance, check out this post to know more about it:
PHP - Inheritance
One important difference is in memory allocation.
When an instance of a class (object) is created, memory is allocated for the newly created object. The name static is after the nature of the memory allocation. That is, memory for static objects are allocated only once, statically. When an object changes it's static property, it reflects on all objects of the same class.
<?php
class Test {
static $test = "world!";
static function hello() {
echo "\nhello " . self::$test . "\n";
}
}
$t = new Test();
$x = new Test();
$t->hello(); // prints 'hello world!'
$t::$test = "Hmmm...";
$t->hello(); // prints 'hello Hmmm...'
$x->hello(); // prints 'hello Hmmm...'
Constant variable is a variable which can be accessed by class name and can NOT be changed during script execution. Class static variable also can be accessed by class name but can be changed during program execution.
Second question - these are COMPLETELY other things. Read more about object oriented programming (not only in PHP)
The reason you'd want to use a static member variable/function is because you can extract information about that class without needing to create an instance of it (which costs you less CPU overhead).
Constant variable are separate for each and every object.
But static variable are common for all object of that class.
Each object share a single static variable.
Static variable created at Class Level.
Constant variable created at instance level.

How to refer to a static constant member variable in PHP

I have a class with member variables. What is the syntax in PHP to access the member variables from within the class when the class is being called from a static context?
Basically I want to call a class method (but not create a new object), but when the class method is called, I want a handful of static constant variables to be initialized that need to be shared among the different class methods.
OR if there's a better way to do it then what I'm proposing, please share with me (I'm new to PHP)
Thanks!
eg.
class example
{
var $apple;
function example()//constructor
{
example::apple = "red" //this throws a parse error
}
}
For brevity sake I will only offer the php 5 version:
class Example
{
// Class Constant
const APPLE = 'red';
// Private static member
private static $apple;
public function __construct()
{
print self::APPLE . "\n";
self::$apple = 'red';
}
}
Basically I want to call a class
method (but not create a new object),
but when the class method is called, I
want a handful of static constant
variables to be initialized that need
to be shared among the different class
methods.
Try this
class ClassName {
static $var;
function functionName() {
echo self::$var = 1;
}
}
ClassName::functionName();

PHP Classes: when to use :: vs. ->?

I understand that there are two ways to access a PHP class - "::" and "->". Sometime one seems to work for me, while the other doesn't, and I don't understand why.
What are the benefits of each, and what is the right situation to use either?
Simply put, :: is for class-level properties, and -> is for object-level properties.
If the property belongs to the class, use ::
If the property belongs to an instance of the class, use ->
class Tester
{
public $foo;
const BLAH;
public static function bar(){}
}
$t = new Tester;
$t->foo;
Tester::bar();
Tester::BLAH;
The "::" symbol is for accessing methods / properties of an object that have been declared with the static keyword, "->" is for accessing the methods / properties of an object that represent instance methods / properties.
Php can be confusing in this regard you should read this.
What's also confusing is that you can call non static functions with the :: symbol. This is very strange when you come from Java. And it certainly surprised me when I first saw it.
For example:
class Car
{
public $name = "Herbie <br/>";
public function drive()
{
echo "driving <br/>";
}
public static function gas()
{
echo "pedal to the metal<br/>";
}
}
Car::drive(); //will work
Car::gas(); //will work
$car = new Car();
$car->drive(); // will work
$car->gas(); //will work
echo $car->name; // will work
echo Car::$name; // wont work error
As you can see static is very loose in php. And you can call any function with both the -> and the :: symbols. But there is a difference when you call with :: there is no $this reference to an instance. See example #1 in the manual.
When you declare a class, it is by default 'static'. You can access any method in that class using the :: operator, and in any scope. This means if I create a lib class, I can access it wherever I want and it doesn't need to be globaled:
class lib
{
static function foo()
{
echo "hi";
}
}
lib::foo(); // prints hi
Now, when you create an instance of this class by using the new keyword, you use -> to access methods and values, because you are referring to that specific instance of the class. You can think of -> as inside of. (Note, you must remove the static keyword) IE:
class lib
{
function foo()
{
echo "hi";
}
}
$class = new lib;
$class->foo(); // I am accessing the foo() method INSIDE of the $class instance of lib.
It should also be noted that every static function can also be called using an instance of the class but not the other way around.
So this works:
class Foo
{
public static function bar(){}
}
$f = new Foo();
$f->bar(); //works
Foo::bar(); //works
And this doesn't:
class Foo
{
protected $test="fddf";
public function bar(){ echo $this->test; }
}
$f = new Foo();
$f->bar(); //works
Foo::bar(); //fails because $this->test can't be accessed from a static call
Of course you should restrict yourself to calling static methods in a static way, because instantiating an instance not only costs memory but also doesn't make much sense.
This explanation was mainly to illustrate why it worked for you some of the times.
:: is used to access a class static property. And -> is used to access a class instance ( Object's ) property.
Consider this Product class that has two functions for retrieving product details. One function getProductDetails belongs to the instance of a class, while the other getProductDetailsStatic belongs to the class only.
class Product {
protected $product_id;
public function __construct($product_id) {
$this->product_id = $product_id;
}
public function getProductDetails() {
$sql = "select * from products where product_id= $this->product_id ";
return Database::execute($sql);
}
public static function getProductDetailsStatic($product_id) {
$sql = "select * from products where product_id= $product_id ";
return Database::execute($sql);
}
}
Let's Get Products:
$product = new Product('129033'); // passing product id to constructor
var_dump( $product->getProductDetails() ); // would get me product details
var_dump( Product::getProductDetailsStatic('129033') ); // would also get me product details
When to you use Static properties?
Consider this class that may not require a instantiation:
class Helper {
static function bin2hex($string = '') {
}
static function encryptData($data = '') {
}
static function string2Url($string = '') {
}
static function generateRandomString() {
}
}
Sourcing WikiPedia - Class
In object-oriented programming, a
class is a programming language
construct that is used as a blueprint
to create objects. This blueprint
describes the state and behavior that
the created objects all share. An
object created by a class is an
instance of the class, and the class
that created that instance can be
considered as the type of that object,
e.g. a type of an object created by a
"Fruit" class would be "Fruit".
The :: operator accesses class methods and properties which are defined in php using the static keyword. Class const are also accessed using ::
The -> operator accesses methods and properties of an Instance of the class.
If the function operates on an instance, you'll be using ->. If it operates on the class itself, you'll be using ::
Another use of :: would be when you want to call your parent functions. If one class inherits another - it can override methods from the parent class, then call them using parent::function()

php static function

I have a question regarding static function in php.
let's assume that I have a class
class test {
public function sayHi() {
echo 'hi';
}
}
if I do test::sayHi(); it works without a problem.
class test {
public static function sayHi() {
echo 'hi';
}
}
test::sayHi(); works as well.
What are the differences between first class and second class?
What is special about a static function?
In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.
Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).
Simply, static functions function independently of the class where they belong.
$this means, this is an object of this class. It does not apply to static functions.
class test {
public function sayHi($hi = "Hi") {
$this->hi = $hi;
return $this->hi;
}
}
class test1 {
public static function sayHi($hi) {
$hi = "Hi";
return $hi;
}
}
// Test
$mytest = new test();
print $mytest->sayHi('hello'); // returns 'hello'
print test1::sayHi('hello'); // returns 'Hi'
Entire difference is, you don't get $this supplied inside the static function. If you try to use $this, you'll get a Fatal error: Using $this when not in object context.
Well, okay, one other difference: an E_STRICT warning is generated by your first example.
Calling non-static methods statically generates an E_STRICT level warning.
In a nutshell, you don't have the object as $this in the second case, as
the static method is a function/method of the class not the object instance.
After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this operator to work on class functions. So I couldn't find a difference in them yet. :(

Categories