Jump to content

Class error handling examples


jodunno
Go to solution Solved by kicken,

Recommended Posts

seeking Class error handling examples not more whining. I'm fed up and seeking examples. Newbie tutorials are offensive.

I am currently taking my first (baby) steps into PHP OOP. I have a read about classes and i've tested a class file with a construct and functions. Once again, php devs make interject like whining babies over minor problems that a dev can handle with code.

Agressive error handling within classes is the scope of my aim here. I have to ask what are pro(fessional) php coders doing about errors in classes? do you not notice how php lays an egg and just shuts down your website to show an error that a developer can handle with proper coding. Hey, php devs: if !is_string(). I can do it myself. No need for an exaggerated bsod.

Anyway, i have found a few tricks that stop this from happening.
1. return false from an if statement in the construct but a property declaration is necessary.
2. return error in the functions when data is a mismatch and return a null coalesce jic (Just incase) php forgets its place.

so far, i am happy with the results.

I want to know what others are doing to prevent all errors other than fatal. I cannot find examples of error handling in classes. I am amazed that i cannot find anything to guide me along. Maybe i am not typing the right phrase.

Anyone have examples of stopping baby whining about minor errros? Have a look at my error thwarting attempts. Have better code? a link to better examples?

<?php declare (strict_types = 1);

Namespace SpyderEyes; // because Reflection Class exists.

class Reflection {

    protected $TEST_mirror;

    public function __construct($TEST_shine) {
        if (!is_string($TEST_shine)/*.*/) { return false; }
        $this->TEST_mirror = $TEST_shine;
    }
    public function TEST_shine(): string {
        if (!is_string($this->TEST_mirror)) { return 'error'; }
        return $this->TEST_mirror ? $this->TEST_mirror : 'empty';
    }
    public function TEST_dust(): string {
        if (!is_string($this->TEST_mirror)) { return 'error'; }
        return $this->TEST_mirror ? bin2hex(base64_encode($this->TEST_mirror)) : 'undusted';
    }
}
    $TEST_reflector = new Reflection(['Mirror, Mirror on the Wall', 'exit']);
    echo '<p>' . $TEST_reflector->TEST_shine() . '</p>' . PHP_EOL;
    echo '<p>' . $TEST_reflector->TEST_dust() . '</p>' . PHP_EOL;
?>

I wonder if php devs forgot about if !is_string. LOL

Best wishes,

John

Link to comment
Share on other sites

32 minutes ago, jodunno said:

Anyone have examples of stopping baby whining about minor errros?

If you don't want PHP to complain about type errors, then stop using strict_types and type hinting.  The whole point of those features is to enforce a specific type, so if you're not passing the correct type it's not a "minor error" it's a real error.

38 minutes ago, jodunno said:

return false from an if statement in the construct but a property declaration is necessary.

You cannot return a value from a constructor.  The correct thing to do if the data in a constructor is invalid is to throw an exception.

39 minutes ago, jodunno said:

return error in the functions when data is a mismatch and return a null coalesce jic (Just incase) php forgets its place.

This all becomes unnecessary if you ensure the constructor either has valid data, or fails with an exception.

Link to comment
Share on other sites

where is the code examples? kicken up dust. I'm happy with my current code. But it all seems like functional programming in a wrapper called a class that just reinvents the wheel imo. Not seeing the benefits yet on the server-side scripting aspect of the www. Meantime, i'll try to find new ways to keep the code in my control without throwing exceptions for a minor nuisance.

<?php declare (strict_types = 1);

Namespace SpyderEyes; // because Reflection Class exists.

class Reflection {

    protected $TEST_mirror;

    function __construct($TEST_shine) {
        //notice the word <i>function</i>. a <i>return</i> is valid within a function.
        $this->TEST_mirror = $TEST_shine;
    }

    function TEST_shine() {
        if (empty($_SESSION['SpyderEyes']['PrivateFunctionKey'])/*.*/) { return 'private function is inaccessible'; }
        if (!is_string($this->TEST_mirror)) { return 'error'; }
        return $this->TEST_mirror ? $this->TEST_mirror : 'empty';
    }
    function TEST_dust() {
        if (empty($_SESSION['SpyderEyes']['PrivateFunctionKey'])/*.*/) { return 'private function is inaccessible'; }
        if (!is_string($this->TEST_mirror)) { return 'error'; }
        return $this->TEST_mirror ? bin2hex(base64_encode($this->TEST_mirror)) : 'undusted';
    }
}   
    $TEST_reflector = new Reflection('Mirror, Mirror, on the wall');
    echo '<p>' . $TEST_reflector->TEST_shine() . '</p>' . PHP_EOL;
    echo '<p>' . $TEST_reflector->TEST_dust() . '</p>' . PHP_EOL;
?>

i also created a private function without specifying it within the class. no key, no code. unset when finished.

i go to bed now and play more tomorrow.

Best wishes, from John.

Link to comment
Share on other sites

  • Solution
6 hours ago, jodunno said:

But it all seems like functional programming in a wrapper called a class that just reinvents the wheel imo.

Maybe because whatever you're doing doesn't need OOP.  Maybe you just don't understand OOP well enough to see the usefulness.  It's hard to say.  The example class you posted here seems pretty pointless.  If you want to see your class fixed up though,

<?php
declare (strict_types=1);

namespace SpyderEyes;

class Reflection {
    protected string $mirror;

    public function __construct(string $shine){
        $this->mirror = $shine;
    }

    public function shine() : string{
        return $this->mirror;
    }

    public function dust() : string{
        return bin2hex(base64_encode($this->mirror));
    }
}

try {
    $reflector = new Reflection(['Mirror, Mirror on the Wall']);
    echo '<p>' . $reflector->shine() . '</p>' . PHP_EOL;
    echo '<p>' . $reflector->dust() . '</p>' . PHP_EOL;
} catch (\TypeError $error){
    echo 'Oops';
}

The constructor will throw a type error if you pass a non-string value which you can catch and handle if you want.  Since the constructor can only accept a string, you ensure that the mirror property will always be a string and thus do not have to do any checking in the individual methods.

 

7 hours ago, jodunno said:

Not seeing the benefits yet on the server-side scripting aspect of the www

One way to dive into the deep end and see how OOP can be beneficial is by looking at the various frameworks that exist.  I like Symfony personally and think spending some time using and learning about it can be quite beneficial in showing how useful an OOP approach can be.

A couple other reasons why classes are nice:

  1. Class autoloading saves you from getting into an include/require nightmare.
  2. IDE's can easily parse the classes and provide auto-completion.

 

7 hours ago, jodunno said:
//notice the word <i>function</i>. a <i>return</i> is valid within a function.

Yes, return is valid in a function.  Returning a value from a constructor is not though.  Take your original code that returned false

class Reflection {
    protected string $mirror;

    public function __construct($shine){
        if (!is_string($shine)){
            return false;
        }
        $this->mirror = $shine;
    }
}

What do you expect return false to do there?  If you think it's something you can test for to see if the constructor failed, you're mistaken

$o = new Reflection([]);
if ($o === false){
   echo 'Oops';
} else {
   echo 'Success!';
}

That if statement will never be true, $o will always be an instance of Reflection.  The return only causes the constructor to stop running, which means your mirror property never gets initialized and thus causes you future issues.

 

7 hours ago, jodunno said:

i also created a private function without specifying it within the class. no key, no code. unset when finished.

This I don't understand at all.  Trying to emulate private functions by checking if some session variable exists make zero sense and doesn't actually make the function private at all since all one would have to do to use it is set that variable.

 

  • Like 1
Link to comment
Share on other sites

functional programming wih a few special terms that only work in classes, id est, this. Have a closer look. If you cannot see it then you are an idiot and an idiot trying to convince others to be an idiot in your likeness. Functional programming. And it is not my problem you cannot remember to include or require a file. LOL.

<?php declare (strict_types = 1);

Namespace SpyderEyes; // because Reflection Class exists.

function Reflection($My_Class) {
    
    if (!is_array($My_Class) || count($My_Class) !== 2) { return 'error'; }
    $My_Constructor = $My_Class[0];
    $Private_Function = $My_Class[1];
    if (!is_string($My_Constructor) || !is_string($Private_Function)/*.*/) { return 'error'; }
    if (!in_array($Private_Function, ['TEST_shine','TEST_dust'], true)/*.*/) { return 'error'; }

    $TEST_shine = function(string $TEST_mirror = '') {
        //if (empty($_SESSION['SpyderEyes']['PrivateFunctionKey'])/*.*/) { return 'private function is inaccessible'; }
        return $TEST_mirror ? $TEST_mirror : 'empty';
    };
    //function TEST_dust(string $TEST_mirror = '') {
    $TEST_dust = function(string $TEST_mirror = '') {
        //if (empty($_SESSION['SpyderEyes']['PrivateFunctionKey'])/*.*/) { return 'private function is inaccessible'; }
        return $TEST_mirror ? bin2hex(base64_encode($TEST_mirror)) : 'undusted';
    };
    return (${$Private_Function})($My_Constructor);

}   
    $New_Reflection1 = Reflection(['Mirror, Mirror, on the wall', 'TEST_shine']);
    $New_Reflection2 = Reflection(['Mirror, Mirror, on the wall', 'TEST_dust']);
    echo '<p>' . $New_Reflection1 . '</p>' . PHP_EOL;
    echo '<p>' . $New_Reflection2 . '</p>' . PHP_EOL;
?>

by the way, stop worrying about the 99percent, of which you are included. The 1percent hacks top Tech companies and kicken, requinix and jodunno combined are not a threat to the 1percent. You know doggone well that you cannot change my session code from the client, so stop leaking noetic venom. You only influence others to learn poor coding skills. Have a look at old php books (4 and 5) and see why hacking has wreaked havoc. You must have written one of those books 0.0

In any event, i always appreciate the tips, opinions, and any help. Thanks for taking time to read and reply. I am not on the class bandwagon at this time. I am going to continue with my spaghetti code. Also, Kicken, your 'cleaned up code' looks good actually but does nothing to control php devs wild lets throw errors for every reason approach to a language. I'd rather make functions and control the code myself.

Best wishes, John.
 

Link to comment
Share on other sites

12 minutes ago, jodunno said:

You know doggone well that you cannot change my session code from the client, so stop leaking noetic venom.

Nor could any client just call your function, so why bother with your private hack in the first place?

Private vs public functions has nothing to do with the client/browser, but with other parts of your code.  A private function can only be called by some other function within the same class, not by code outside that class.  Public function can be called by any part of your code.  It may seem pointless when your just developing some small-time blog made out of one page and a couple includes but when you get into real programming work it becomes important.

I feel like you are either trolling or just feel like your smarter than everyone else.  Seems obvious at least that you have no interest in actually learning programming techniques.

17 minutes ago, jodunno said:

I am going to continue with my spaghetti code.

By all means, keep that hot garbage you call code for yourself, nobody wants it.

  • Thanks 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.