<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
$apple = new Fruit("Apple", "red");
?>
C
เป็น function พิเศษ ในภาษาC ที่จะใช้ในการคืนพื้นที่ ที่ obj ใช้
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name;
int age;
} Person;
// Function to create a new Person
Person* create_person(const char *name, int age) {
Person *p = (Person *)malloc(sizeof(Person));
if (p == NULL) {
perror("Failed to allocate memory");
return NULL;
}
p->name = (char *)malloc(strlen(name) + 1);
if (p->name == NULL) {
perror("Failed to allocate memory for name");
free(p);
return NULL;
}
strcpy(p->name, name);
p->age = age;
return p;
}
// Function to "destruct" or clean up a Person
void destroy_person(Person *p) {
if (p != NULL) {
free(p->name); // Free the name memory
free(p); // Free the Person struct memory
}
}
int main() {
Person *person = create_person("Alice", 30);
if (person != NULL) {
printf("Name: %s, Age: %d\n", person->name, person->age);
destroy_person(person); // Call the destructor-like function
}
return 0;
}
public class DestructorExample
{
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
de.finalize();
de = null;
System.gc();
System.out.println("Inside the main() method");
}
protected void finalize()
{
System.out.println("Object is destroyed by the Garbage Collector");
}
}
# Python program to illustrate destructor
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj