Přidat otázku mezi oblíbenéZasílat nové odpovědi e-mailem Jak vytvořit return true/false

Ahoj, jak bych mohl doplnit tuto funkci o return true / false, pokud cokoli selže tak false a pokud je všechno ok tak true. Může někdo poradit?

function write (){
$file = 'people.txt';
$current = file_get_contents($file); // Open the file to get existing content
$current .= "John Smith\n"; // Append a new person to the file
file_put_contents($file, $current); // Write the contents back to the file
}
Předmět Autor Datum
function write (){ $file = 'people.txt'; try { $current = file_get_contents($file); // Open the file…
Wikan 21.04.2018 19:01
Wikan
Díky pane a je možnost i bez použití vyjímky byť třeba jen s jedním returnem?
Mark-y 21.04.2018 19:06
Mark-y
Na otevírání a práci se soubory, vždy používat TRY/CATCH. Samozřejmě tu funkci ještě musíš deklarova…
antibalda 21.04.2018 19:08
antibalda
A jak se taková funkce deklaruje jako bool? Tím, že vrací true nebo false přece return bool je, ne? poslední
Mark-y 21.04.2018 19:20
Mark-y
function write (){ $file = 'people.txt'; $current = file_get_contents($file); // Open the file to ge…
Wikan 21.04.2018 19:14
Wikan
Díky moc.
Mark-y 21.04.2018 19:19
Mark-y
function write (){
    $file = 'people.txt';
    try {
        $current = file_get_contents($file); // Open the file to get existing content
        $current .= "John Smith\n"; // Append a new person to the file
        file_put_contents($file, $current); // Write the contents back to the file
        return true;
    } catch (Exception $e) {
        return false;
    }
}
function write (){
    $file = 'people.txt';
    $current = file_get_contents($file); // Open the file to get existing content
    if ($current === false) {
        return false;
    }
    $current .= "John Smith\n"; // Append a new person to the file
    return file_put_contents($file, $current) !== false; // Write the contents back to the file
}

Zpět do poradny Odpovědět na původní otázku Nahoru