PHP Strict Typing with Declare Control Structure

PHP Strict Typing Check with Declare Control Structure

PHP তে declare Control Structure কি?

PHP-তে declare() কন্ট্রোল স্ট্রাকচার কোড ব্লকের জন্য নির্দিষ্ট নির্দেশনা বা কনফিগারেশন অপশন গুলো সেট করতে ব্যবহৃত হয়। এটি আপনাকে আপনার স্ক্রিপ্টের একটি নির্দিষ্ট অংশ যেমন, আপনার বর্তমান ফাইল এর জন্য PHP interpreter এর বিহেভিয়ার পরিবর্তন করতে দেয়। declare() construct প্রাথমিকভাবে error handling, strict typing check এবং Ticks সহ অন্যান্য runtime কনফিগারেশনের মতো দিকগুলি নিয়ন্ত্রণ করতে ব্যবহৃত হয়।

Strict Typing Check কি?

পিএইচপি-তে Strict typing একটি ফীচার যা ফাংশন parameters এবং return value গুলির জন্য শক্তিশালী data type checking প্রয়োগ করে। আর এর জন্য একজন প্রোগ্রামারকে declare(strict_types=1) ফাঙ্কশনটি ব্যবহার করতে হয়। একটি script বা ফাইলের শুরুতে, PHP নিশ্চিত করে যে data type গুলি সঠিকভাবে মিলেছে এবং এটি PHP এর Loosly Typing সুবিধা বন্ধ করে । যদি নির্ধারিত Type এর ডাটা পাঠানো না হয়। তাহলে PHP একটি TypeError throw করে এবং সাথে সাথে script execution বন্ধ করে।

PHP তে কিভাবে strict typing checking সুবিধা সক্রিয় করব ?

PHP তে strict typing checking সুবিধা সক্রিয় করতে হলে আপনাকে PHP ফাইলের একদম শুরুতে declare(strict_types=1) ফাঙ্কশনটি এবং তার ভিতরে parameter হিসেবে strict_types=1 ব্যবহার করতে হবে।

PHP তে strict type checking কোথায় প্রয়োগ করা যাবে?

PHP তে আপনি strict type checking দুই জায়গায় করতে পারেন :

  • Function এর Parameter Types এ strict typing checking
  • Function এর Return Value Types এ strict typing checking

Zend Certified PHP Engineering (ZCPE) Course

Function এর Parameter Types এ strict typing checking

যখন strict typing এনাবল করা হয়, তখন function এর parameter গুলি অবশ্যই তাদের ঘোষিত types সাথে স্পষ্টভাবে মেলতে হবে । যদি একটি function একটি int parameter আশা করে, তাহলে এটি অবশ্যই একটি int গ্রহণ করবে এবং অন্য কোনো ডেটা টাইপ এসে থাকে, তাহলে একটি TypeError হবে।

নিচের উদাহরণ লক্ষ্য করুন :

declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

$result = add(5, 3); // This is valid because both arguments are integers.
$result = add("5", "3"); // This will throw a TypeError due to strict typing.

Function এর Return Value Types এ strict typing checking

যখন একটি function একটি return type ঘোষণা করে, strict typing নিশ্চিত করে যে ফাংশনটি নির্দিষ্ট type একটি মান return করবে। যদি ফাংশন সঠিক ডেটা টাইপ return না করে, তাহলে একটি TypeError throw করা হবে ।

নিচের উদাহরণ লক্ষ্য করুন :

declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b+ 2.5;
}

$result = add(5, 3); // This is valid because the return type is int.
$result = add(2, 5); // This will throw a TypeError because the return type is int.

type-related bug গুলো এড়ানোর এবং প্রতিরোধ এবং code reliability উন্নত করার জন্য Strict typing বিশেষভাবে কার্যকর। এটি ডেভেলপমেন্ট এর প্রাথমিক পর্যায়ে type mismatche প্রতিরোধ করতে সাহায্য করে, এটি কোড মেইনটেইন রাখা এবং debug করা সহজ করে তোলে।

যাইহোক, সব PHP প্রজেক্টের জন্য strict typing সবসময় প্রয়োজনীয় নয়, এবং অনেক সময় একটি নির্দিষ্ট পরিস্থিতিতে আমাদের type casting প্রয়োজন হতে পারে। অতএব, strict typing ব্যবহার করা বা না করা আপনার প্রজেক্টের প্রয়োজনীয়তা এবং কোডিং স্ট্যান্ডার্ড এর উপর নির্ভর করে। এটি একটি মূল্যবান সুবিধা , বিশেষ করে বৃহত্তর কোডবেসে বা যখন ডেটা টাইপের সামঞ্জস্য গুরুত্বপূর্ণ।

এবার চলুন একটা প্রফেশনাল উদাহরণ দেখে নেয়া যাক :

এই উদাহরণে, আমরা BankAccount নামে একটি ক্লাস তৈরি করব যা strict typing সহ একটি সাধারণ ব্যাঙ্কিং অ্যাকাউন্টের রিপ্রেজেন্ট করবে এবং এর ব্যবহার প্রদর্শন করবে। এতে অ্যাকাউন্ট ব্যালেন্স বজায় রেখে deposit এবং withdraw মেথড অন্তর্ভুক্ত থাকবে।

<?php

declare(strict_types=1);

class BankAccount {
    private string $accountHolder;
    private float $balance;

    public function __construct(string $accountHolder, float $initialBalance = 0.0) {
        $this->accountHolder = $accountHolder;
        $this->balance = $initialBalance;
    }

    public function deposit(float $amount): void {
        if ($amount <= 0) {
            throw new InvalidArgumentException("Deposit amount must be greater than zero.");
        }
        $this->balance += $amount;
    }

    public function withdraw(float $amount): void {
        if ($amount <= 0) {
            throw new InvalidArgumentException("Withdrawal amount must be greater than zero.");
        }
        if ($amount > $this->balance) {
            throw new RuntimeException("Insufficient funds to withdraw $amount.");
        }
        $this->balance -= $amount;
    }

    public function getBalance(): float {
        return $this->balance;
    }

    public function getAccountHolder(): string {
        return $this->accountHolder;
    }
}

// Usage
$account = new BankAccount("John Doe", 1000.0);

echo "{$account->getAccountHolder()}'s initial balance: {$account->getBalance()}\n";

$account->deposit(500.0);
echo "After depositing $500, {$account->getAccountHolder()}'s balance: {$account->getBalance()}\n";

try {
    $account->withdraw(1500.0); // Attempting to withdraw more than the balance
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

$account->withdraw(300.0);
echo "After withdrawing $300, {$account->getAccountHolder()}'s balance: {$account->getBalance()}\n";
?>

এই উদাহরণে:

  • আমরা properties এবং method parameter গুলির জন্য strict typing সহ একটি BankAccount class তৈরি করি।
  • ক্লাসে depositing, withdrawing এবং account balance পাওয়ার methods গুলো রয়েছে।
  • withdraw method ব্যবহার করার সময়, আমরা current balance এর চেয়ে উত্তোলনের পরিমাণ বেশি কিনা তা পরীক্ষা করি এবং এটি পর্যাপ্ত না হলে একটি exception throw করি।
  • আমরা withdrawal এর সময় insufficient funds এর মতো পরিস্থিতিতে exception গুলি catch করতে error handling ও অন্তর্ভুক্ত করি।
  • usage section টি একটি account, depositing এবং withdrawing funds এবং অ্যাকাউন্টধারীর তথ্য এবং ব্যালেন্স প্রদর্শন করে।

এই কোডটি একটি banking account এর প্রতিনিধিত্বকারী একটি class এর সাথে PHP strict typing এর একটি আরও professional এবং real-world use case দেখায়।

Zend Certified PHP Engineering (ZCPE) Course

এবার আসুন একটি simple e-commerce shopping cart system তৈরি করে PHP strict typing এর আরও ব্যবহারিক এবং real-world উদাহরণ অন্বেষণ করি। আমরা products, একটি shopping cart প্রতিনিধিত্ব করার জন্য দুটি class তৈরি করব এবং সিস্টেমের মধ্যে বিভিন্ন operations সম্পাদন করব।

<?php

declare(strict_types=1);

class Product {
    private string $name;
    private float $price;

    public function __construct(string $name, float $price) {
        $this->name = $name;
        $this->price = $price;
    }

    public function getName(): string {
        return $this->name;
    }

    public function getPrice(): float {
        return $this->price;
    }
}

class ShoppingCart {
    private array $items = [];

    public function addItem(Product $product, int $quantity): void {
        if ($quantity <= 0) {
            throw new InvalidArgumentException("Quantity must be greater than zero.");
        }
        if (isset($this->items[$product->getName()])) {
            $this->items[$product->getName()]['quantity'] += $quantity;
        } else {
            $this->items[$product->getName()] = ['product' => $product, 'quantity' => $quantity];
        }
    }

    public function removeItem(string $productName): void {
        if (isset($this->items[$productName])) {
            unset($this->items[$productName]);
        }
    }

    public function getTotal(): float {
        $total = 0.0;
        foreach ($this->items as $item) {
            $total += $item['product']->getPrice() * $item['quantity'];
        }
        return $total;
    }

    public function getItems(): array {
        return $this->items;
    }
}

// Usage
$product1 = new Product("Laptop", 999.99);
$product2 = new Product("Mouse", 29.99);

$cart = new ShoppingCart();

$cart->addItem($product1, 2);
$cart->addItem($product2, 3);

echo "Shopping Cart Contents:\n";
foreach ($cart->getItems() as $item) {
    echo "{$item['product']->getName()} (Quantity: {$item['quantity']}) - {$item['product']->getPrice()} USD each\n";
}

echo "Total Price: {$cart->getTotal()} USD\n";

এই real-world উদাহরণে:

  • আমাদের একটি Product class রয়েছে যা name এবং price attributes গুলির জন্য strict typing সহ products গুলিকে রিপ্রেজেন্ট করে।
  • ShoppingCart class টি এমন একটি shopping cart প্রতিনিধিত্ব করে যাতে methods এর জন্য strict typing করা হয় যা $product এর জন্য Product objects এবং $quantity এর জন্য integers গ্রহণ করে।
  • shopping cart এ আইটেম adding এবং removing এবং total price calculating সমর্থন করে।
  • Item add করার সময় পরিমাণ শূন্যের চেয়ে বেশি তা নিশ্চিত করার জন্য Error handling অন্তর্ভুক্ত করা হয়েছে।
  • usage section এ product তৈরি করা, shopping cart এ সেগুলো যোগ করা এবং total price calculate করা দেখায়।

এই উদাহরণটি দেখায় যে কীভাবে strict typing ব্যবহারিক পরিস্থিতিতে ব্যবহার করা যেতে পারে, যেমন একটি ই-কমার্স সিস্টেমে products গুলি এবং একটি shopping cart পরিচালনা করা।

আমি মাসুদ আলম, বাংলাদেশের ৩৬ তম Zend Certified Engineer । ২০০৯ সালে কম্পিউটার সাইন্স থেকে বেচেলর ডিগ্রী অর্জন করি। দীর্ঘ ১৫ বছর আমি Winux Soft, SSL Wireless, IBCS-PRIMAX, Max Group, Canadian International Development Agency (CIDA), Care Bangladesh, World Vision, Hellen Keller, Amarbebsha Ltd সহ বিভিন্ন দেশি বিদেশী কোম্পানিতে ডেটা সাইন্স, মেশিন লার্নিং, বিগ ডেটা, ওয়েব ডেভেলপমেন্ট এবং সফটওয়্যার ডেভেলপমেন্ট এর উপর বিভিন্ন লিডিং পজিশন এ চাকরি এবং প্রজেক্ট লিড করি। এছাড়াও বাংলাদেশের ১৮৫ জন জেন্ড সার্টিফাইড ইঞ্জিনিয়ার এর মধ্যে ১২০ এরও অধিক ছাত্র আমার হাতে জেন্ড সার্টিফাইড ইঞ্জিনিয়ার হয়েছেন। বর্তমানে w3programmers ট্রেনিং ইনস্টিটিউট এ PHP এর উপর Professional এবং Advance Zend Certified PHP -8.2 Engineering, Laravel Mastering Course with ReactJS, Python Beginning To Advance with Blockchain, Machine Learning and Data Science, Professional WordPress Plugin Development Beginning to Advance কোর্স করাই। আর অবসর সময়ে w3programmers.com এ ওয়েব টেকনোলজি নিয়ে লেখালেখি করি।

Leave a Reply