What Is ::Class in PHP

what is ::class php in laravel

Answer:

Using that ::class syntax allows you to declare a class without
passing it as a string. When they update ide's it will help to auto
fill namespaces which can't be done with a string.

Source Information:

Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes.

Example #10 Class name resolution

<?php
namespace NS {
class ClassName {
}

echo ClassName::class;
}
?>

The above example will output:

NS\ClassName

Note:

The class name resolution using ::class is a compile time
transformation. That means at the time the class name string is
created no autoloading has happened yet. As a consequence, class names
are expanded even if the class does not exist. No error is issued in
that case.

Source Link :: Php Manual

PHP: What does ::class do?

from PHP doc
"Since PHP 5.5, the class keyword is also used for class name resolution. You can get a string containing the fully qualified name of the ClassName class by using ClassName::class. This is particularly useful with namespaced classes."

<?php
namespace NS {

class ClassName {

}

echo ClassName::class;
}
?>

http://php.net/manual/en/language.oop5.basic.php

What is a class in PHP?

In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.


Imagine a Lock:

namespace MyExample;

class Lock
{
private $isLocked = false;

public function unlock()
{
$this->isLocked = false;
echo 'You unlocked the Lock';
}
public function lock()
{
$this->isLocked = true;
echo 'You locked the Lock';
}
public function isLocked()
{
return $this->isLocked;
}
}

Ignore the namespace, private and public declaration right now.

The Lock class is a blueprint for all the Locks in your application. A Lock can either be locked or unlocked, represented by the property $isLocked. Since it can have only these two states, I use a Boolean (true or false) to indicate which state applies. I can interact with the Lock through it's methods lock and unlock, which will change the state accordingly. The isLocked method will give me the current state of the Lock. Now, when you create an object (also often referred to as an instance) from this blueprint, it will encapsulate unique state, e.g.

$aLock = new Lock; // Create object from the class blueprint
$aLock->unlock(); // You unlocked the Lock
$aLock->lock(); // You locked the Lock

Let's create another lock, also encapsulating it's own state

$anotherLock = new Lock;
$anotherLock->unlock(); // You unlocked the Lock

but because each object/instance encapsulates it's own state, the first lock stays locked

var_dump( $aLock->isLocked() );       // gives Boolean true
var_dump( $anotherLock->isLocked() ); // gives Boolean false

Now the entire reponsibility of keeping a Lock either locked or unlocked is encaspulated within the Lock class. You don't have to rebuilt it each time you want to lock something and if you want to change how a Lock works you can change this in the blueprint of Lock instead of all the classes having a Lock, e.g. a Door:

class Door
{
private $lock;
private $connectsTo;

public function __construct(Lock $lock)
{
$this->lock = $lock;
$this->connectsTo = 'bedroom';
}
public function open()
{
if($this->lock->isLocked()) {
echo 'Cannot open Door. It is locked.';
} else {
echo 'You opened the Door connecting to: ', $this->connectsTo;
}
}
}

Now when you create a Door object you can assign a Lock object to it. Since the Lock object handles all the responsibility of whether something is locked or unlocked, the Door does not have to care about this. In fact any objects that can use a Lock would not have to care, for instance a Chest

class Chest
{
private $lock;
private $loot;

public function __construct(Lock $lock)
{
$this->lock = $lock;
$this->loot = 'Tons of Pieces of Eight';
}
public function getLoot()
{
if($this->lock->isLocked()) {
echo 'Cannot get Loot. The chest is locked.';
} else {
echo 'You looted the chest and got:', $this->loot;
}
}
}

As you can see, the reponsibility of the Chest is different from that of a door. A chest contains loot, while a door separates rooms. You could code the locked or unlocked state into both classes, but with a separate Lock class, you don't have to and can reuse the Lock.

$doorLock = new Lock;
$myDoor = new Door($doorLock);

$chestLock = new Lock;
$myChest new Chest($chestLock);

Chest and Door now have their unique locks. If the lock was a magical lock that can exist in multiple places at the same time, like in Quantum physics, you could assign the same lock to both chest and door, e.g.

$quantumLock = new Lock;
$myDoor = new Door($quantumLock);
$myChest new Chest($quantumLock);

and when you unlock() the $quantumLock, both Door and Chest would be unlocked.

While I admit Quantum Locks are a bad example, it illustrates the concept of sharing of objects instead of rebuilding state and responsibility all over the place. A real world example could be a database object that you pass to classes using the database.

Note that the examples above do not show how to get to the Lock of a Chest or a Door to use the lock() and unlock() methods. I leave this as an exercise for your to work out (or someone else to add).

Also check When to use self over $this? for a more in-depth explanation of Classes and Objects and how to work with them

For some additional resources check

  • http://en.wikipedia.org/wiki/Object-oriented_programming
  • http://www.php.net/manual/en/language.oop5.php
  • http://www.tuxradar.com/practicalphp
  • http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html
  • http://articles.sitepoint.com/article/object-oriented-php

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

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;

What is the difference between class and function in php?

The PHP Language reference has details on what a function and class is:
http://www.php.net/manual/en/langref.php

It also explains most the other features of PHP. If want to learn PHP that is the best place to start.

Functions

The function is a grouping of statements (lines of code).

For example the following statements:

$name = 'mary';
$gender = 'girl';
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;

Can be grouped together into a function so it can be reused:

getSentence('mary', 'girl');
getSentence('peter', 'boy');
function getSentence($name, $gender) {
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;
}

Notice the two function calls:

getSentence('mary', 'girl');
getSentence('peter', 'boy');

These two statements run the whole block of code inside the getSentence function and pass it the variables $name and $gender.
With the first function $name = 'mary' and $gender = 'girl' and in the second $name = 'peter' and $gender = 'boy'.

So the main benefit of functions is that you have grouped code for reuse, allowing the passing of different values for the variables needed by the function. These variables are called the function parameters.

Another benefit of having the code grouped is easier readability. You are essentially naming the block of code, and giving them a specific purpose. Making it easy to read and remember it's use.

Another benefit is that redundancy is removed. You do not have to write the block of code more then once. You just define it once, and call it multiple times. This also makes editing of the function code affect all calls to that function - which reduces errors in having to edit multiple locations when changing just one aspect.

eg:

We can make sure the $name string has an uppercase first character.

function getSentence($name, $gender) {
$name = ucfirst($name);
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;
}

We made just one change, and it affected every function call to getSentence(). In this case both:

getSentence('mary', 'girl'); 

and

getSentence('peter', 'boy'); 

Classes are a grouping of functions.

class Play {
function getSentence($name, $gender) {
$name = ucfirst($name);
if ($gender == 'girl') {
$line = $name . ' had a little pony.';
} else if ($gender == 'boy') {
$line = $name . ' had a little horse.';
}
echo $line;
}
function getSong($name) {
// code here
}
}

All we did was put

class Play { /** functions here **/ }

around a group of functions.

This offers the same benefits that functions do for statements except classes does it for functions.

Classes go further to build a programming methodology called Object Oriented programming (OOP), which you can read more about in link to PHP Language reference.

This defines classes as the template or definition of Objects. Objects being similar to real world objects, with the functions being called "methods" that can be called for the object.

So the class Play can be thought of as the object called "Play" with the methods "getSentence" and "getSong". These methods can then manipulate the properties of the object "Play" or return useful information about "Play". In this way, all the code inside Play becomes independent of code elsewhere in the program.

When the code inside Play requires some code elsewhere to function, it can be brought in using "inheritance", which is a major part of OOP. I will not go into detail about this as it is a very broad topic.

I would recommend getting a book on OOP and reading it to really understand why you should use classes and methods and when to use them.

Difference between object and class in PHP?

I assume you have read the manual on basic PHP OOP.

A class is what you use to define the properties, methods and behavior of objects. Objects are the things you create out of a class. Think of a class as a blueprint, and an object as the actual building you build by following the blueprint (class). (Yes, I know the blueprint/building analogy has been done to death.)

// Class
class MyClass {
public $var;

// Constructor
public function __construct($var) {
echo 'Created an object of MyClass';
$this->var = $var;
}

public function show_var() {
echo $this->var;
}
}

// Make an object
$objA = new MyClass('A');

// Call an object method to show the object's property
$objA->show_var();

// Make another object and do the same
$objB = new MyClass('B');
$objB->show_var();

The objects here are distinct (A and B), but they are both objects of the MyClass class. Going back to the blueprint/building analogy, think of it as using the same blueprint to build two different buildings.

Here's another snippet that actually talks about buildings if you need a more literal example:

// Class
class Building {
// Object variables/properties
private $number_of_floors = 5; // Each building has 5 floors
private $color;

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

public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}

// Build a building and paint it red
$bldgA = new Building('red');

// Build another building and paint it blue
$bldgB = new Building('blue');

// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
$bldgB->describe();

When to use a Class vs. Function in PHP

Classes are used for representing data as objects. If you're representing something like a user's data, or an auction bid, creating a User object or AuctionBid object makes it easier to keep that data together, pass it around in your code, and make it more easily understandable to readers. These classes would have attributes (data fields like numbers, strings, or other objects) as well as methods (functions that you can operate on any class).

Classes don't usually offer any benefits in terms of performance, but they very rarely have any negative effects either. Their real benefit is in making the code clearer.

I recommend you read the PHP5 Object-Oriented Programming guide and the Wikipedia OOP entry.

PHP Class for adding two numbers

You did not assign the parameters to the object properties in the constructor:

$this->num1 = $num1;
$this->num2 = $num2;


Related Topics



Leave a reply



Submit