1. Go to this page and download the library: Download samueldmonteiro/result-type library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
samueldmonteiro / result-type example snippets
/**
* @return Result<float>
*/
function safeDivide(float $value): Result
{
return $value;
}
use Samueldmonteiro\Result\Error;
use Samueldmonteiro\Result\Result;
use Samueldmonteiro\Result\Success;
/**
* @return Result<float>
*/
function safeDivide(float $a, float $b): Result
{
if ($b === 0.0) {
// Return an error if division by zero
return new Error('Division by zero is not allowed.');
}
return new Success($a / $b, 'Division successful.');
}
// Example usage
$result = safeDivide(10, 2);
if ($result->isSuccess()) {
echo $result->getMessage() . PHP_EOL;
echo "Result: " . $result->getValue() . PHP_EOL;
} else {
echo "Error: " . $result->getErrorMessage() . PHP_EOL;
}
/**
* @return Result<float>
*/
function safeDivide(float $a, float $b): Result
{
if ($b === 0.0) {
return Result::error('Division by zero is not allowed.');
}
return Result::success(($a / $b, 'Division successful.');
}