DeveloperBreeze

PHP Class and Object Example

// Define a Person class
class Person {
    // Private property to store the person's name
    private $name;

    // Constructor to initialize the person's name
    public function __construct($name) {
        $this->name = $name;
    }

    // Method to greet the person
    public function greet() {
        return 'Hello, my name is ' . $this->name;
    }
}

// Create an instance of the Person class with the name 'Alice'
$person = new Person('Alice');

// Call the greet method and echo the result
echo $person->greet();

Related Posts

More content you might like

Tutorial
javascript

Understanding JavaScript Classes

The super keyword is used to call the constructor or methods of the parent class. This is particularly useful when you need to add functionality to a subclass while still retaining the behavior of the parent class.

class Animal {
  constructor(type, name) {
    this.type = type;
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super('Dog', name);
    this.breed = breed;
  }

  speak() {
    super.speak(); // Call the parent class's speak method
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak();
// Output:
// Buddy makes a noise.
// Buddy barks.

Sep 02, 2024
Read More
Code
javascript

JavaScript Class with Constructor and Method

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Class with Method

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!