What are anonymous functions and closures in PHP? PHP में anonymous functions और closures क्या हैं?
Short Answer
Generating a bar graph natively in pure PHP requires using the GD library or Imagick to draw pixels, which is tedious. The modern, best-practice approach is to generate the data in PHP, pass it to the frontend via JSON, and use a JavaScript library like Chart.js.
Detailed Example (Using Chart.js)
Here is how you bridge PHP and a frontend graphing library.
1. Prepare the Data in PHP
// Imagine this data came from a database query
$salesData = [
'January' => 150,
'February' => 200,
'March' => 180
];
// Convert to JSON so JavaScript can read it easily
$labels = json_encode(array_keys($salesData));
$values = json_encode(array_values($salesData));
2. Render the Chart in HTML/JS
<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar', // Specify bar graph
data: {
labels: <?php echo $labels; ?>,
datasets: [{
label: 'Monthly Sales',
data: <?php echo $values; ?>,
backgroundColor: 'rgba(54, 162, 235, 0.5)'
}]
}
});
</script>
Anonymous function बिना नाम का फंक्शन है, अक्सर callback के तौर पर इस्तेमाल होता है। Closure ऐसा anonymous function है जो use कीवर्ड से बाहरी scope के वेरिएबल्स capture करता है।
$multiplier = 3;\n$multiply = function ($x) use ($multiplier) {\n return $x * $multiplier;\n};\necho $multiply(5); // 15\n\n// Arrow function (PHP 7.4+) खुद बाहरी scope capture करता है\n$multiplyArrow = fn($x) => $x * $multiplier; | कॉन्सेप्ट | डिटेल |
|---|---|
| use ($var) | वैल्यू से capture (कॉपी) |
| use (&$var) | रेफरेंस से capture (लाइव लिंक) |
| आम इस्तेमाल | array_map, array_filter, usort callbacks |
इंटरव्यू टिप: by-value बनाम by-reference capture समझाएं — यह एक आम follow-up सवाल है।
Was this answer clear?