Php new class
Here is an example of how to create a new class in PHP:
<?php
class MyClass {
// Properties (data members)
public $name;
public $age;
// Constructor (special method that runs when an object is created)
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Methods (functions that belong to the class)
public function sayHello() {
echo "Hello, my name is ". $this->name. " and I am ". $this->age. " years old.";
}
}
// Create an object from the class
$obj = new MyClass("John", 30);
// Call a method on the object
$obj->sayHello();
?>
This code defines a class called MyClass
with two properties: name
and age
. The constructor method __construct
is called when an object is created, and it sets the values of the name
and age
properties. The sayHello
method is a simple method that prints a greeting message to the screen.
The last two lines of code create an object from the class using the new
keyword, and then call the sayHello
method on the object.
You can also define methods that take parameters, like this:
public function add($a, $b) {
return $a + $b;
}
And then call the method like this:
$result = $obj->add(2, 3);
echo $result; // Output: 5
You can also define private and protected properties and methods, which can only be accessed within the class or by subclasses.
You can also use interfaces and abstract classes to define a contract or a blueprint for a class.
It's worth noting that in PHP, classes are not strictly typed, meaning that you can assign a value of one type to a property or method that is declared as a different type. However, it's generally a good practice to follow type hints and return types to make your code more readable and maintainable.