How to check for a variable existence by a private function in a php Class?

php check if function exists in class
php abstract class
php class variables
php private function outside class
php class visibility
php call private function inside class
php property exists
php class public variable

Here is a pseudo code of what I want to do:

class Test {

  protected  $myVar;

  public function __construct(){
      // get data from DB, returns null if not exist
      $this->myVar = getDataFromDatabase();
  }

  public function myFunc(){

       if(!$this->myVar){
           return response(['message' => 'data not found'],404);
       }

       // do other stuff
  }      
}

This code is working well. Now I want to declare a private function to check for the existence of a variable (To clean my code and use the function everywhere).

This is what I tried :

  public function myFunc(){

       $this->checkExistence();

       // do other stuff
  }  

  private function checkExistence(){
      if(!$this->myVar){
        return response(404);
      }
  }

But it is not working because I do not return the $this->checkExistence();!

And when I try to return it:

return $this->checkExistence();

It's working but the problem is when $myVar exists it is not hitting // do other stuff line because it is returning the whole function that makes sense!

How should I transfer this existence checking to private function!?

If you want to return a response somewhere out of the controller you can always use the abort() method. As the Laravel docs say:

The abort function throws an HTTP exception which will be rendered by the exception handler.

The method accepts a response code, but also a Response class (as you can see here). If you'd like to return a JSON response you could use the following code:

abort(response()->json([], 404));

Visibility - Manual, Class properties must be defined as public, private, or protected. Note: The PHP 4 method of declaring a variable with the var keyword is still $myclass2-> Foo2(); // Public and Protected work, not Private class Bar { public function test() { PHP | Check if a variable is a function. To determine whether a passed argument is a function or not, Few of the most preferred methods are shown below. Using is_callable () Function: It is an inbuilt function in PHP which is used to verify the contents of a variable in called as a function. It can check that a simple variable contains the name of a valid function, or that an array contains a properly encoded object and function name.

You could throw a (custom) exception, and handle the exception in myFunc();

  public function myFunc()
  {
       try {
           $this->checkExistence();
           // do other stuff
       } catch (\My\Namespace\ExistenceException $e) {
           //Handle error
           return response(404);
       }
  }  

  /**
  * @throws \My\Namespace\ExistenceException
  */
  private function checkExistence(): void
  {
      if(!$this->myVar){
        throw new \My\Namespace\ExistenceException;
      }
  }

method_exists - Manual, method_exists — Checks if the class method exists given function has been defined; is_callable() - Verify that the contents of a variable can be called as a function That private/protected methods are seen as callable when tested publicly. This function checks if the given property exists in the specified class.. Note: . As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

The best and easiest for you would be an else clause in your private method. Code after return statement doesn't run, hence an "else" is mandatory in your case. Also, do try to typehint your $myVar to your constructor as well.

    public function __construct($myVar)
     {
        //assign here as you've done
     }

property_exists - Manual, This function checks if the given property exists in the specified class. in the class declaration, or has been added dynamically, if the variable has been unset () property_exists from a parent class sees private properties in sub-classes. method_exists() - Checks if the class method exists is_callable() - Verify that the contents of a variable can be called as a function get_defined_functions() - Returns an array of all defined functions

I would recommend against returning response in your checkExistence() method. Instead, I would have that method return true or false and return the response in the myFunc():

public function myFunc(){
    if (this->checkExistence()) {
        return response(404);
        // Or better yet, use: `abort(404);`
    }
    // do other stuff
}  

private function checkExistence(){
    return !$this->myVar;
}

4. Introduction to Object-Oriented Programming with PHP 5, Here is a pseudo code of what I want to do: class Test { protected $myVar; public function __construct(){ // get data from DB, returns null if not exist $this->myVar� function_exists() - Return TRUE if the given function has been defined; is_callable() - Verify that the contents of a variable can be called as a function; class_exists() - Checks if the class has been defined

you don't want to check if the variable is false-ish (which in PHP includes bool(false) and NULL and emptystring and non-existing property and empty array and god knows what else), you want to check if the property exists, right? in which case, use property_exists, eg

  private function checkExistence(){
      if(!property_exists($this,'myVar'){
        return response(404);
      }
  }

Properties - Manual, Selection from Web Database Applications with PHP and MySQL, 2nd Edition [ Book] For instance, in Chapter 7 we'll show you how to standardize the look of your own To use the member variables and functions defined in a class, an instance of the Member variables can also be defined with the private and protected� If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used use a amespaced\classname as coolclass; class_exists( 'coolclass' ) => false

9. Rules list — Exakat 1 documentation, They are defined by using one of the keywords public, protected, or private, optionally The pseudo-variable $this is available inside any class method when that method is called You might want to take a look at the Class/Object Functions. The isset () function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false. Note: If multiple variables are supplied, then this function will return true only if all of the variables are set.

PHP Access Modifiers, Cache Variable Outside Loop. 9.63.1. Functions Removed In PHP 5.5. 9.218.1 Method Could Be Private Method; 9.299. Method Methods or properties with the same name, are defined static in one class, and not static in another. When a property has to be checked once for existence, it is safer to check it each time. PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks

Implementing Private Variables In JavaScript, PHP provides access modifiers to control the access of variables of a class for PHP classes and its member functions. final : The class methods defined as final, Now that we know which access modifier is used where, lets learn about the� For example, if name exists in a restricted folder to which MATLAB ® does not have access, exist returns 0. 1 — name is a variable in the workspace. 2 — name is a file with extension.m,.mlx, or.mlapp, or name is the name of a file with a non-registered file extension (.mat,.fig,.txt).

Comments
  • try if($this->checkExistence()){...}else{...}
  • where do you call this function?
  • If you want to return a 404 response there, you could use the abort() method.
  • @DanyalSandeelo I am calling it in myFunc function. take a look at my second pseudo code.
  • @DeesOomens you are right. But actually I want to return a json response with 404 code. Will update the question
  • I already doing this by : return response([ 'message' => 'data not found' ], 404);
  • And it's working well and returns HTTP Exception, but when I put this code in a private function it is not wotrking
  • What do you mean by not working? It isn't return a JSON response?
  • public function myFunc(){ RETURN $this->checkExistence(); } And checkExistense() return whatever you need.
  • @DeesOomens Sorry forgot to remove return from myFunct , Now its working but abort only accept int for the first arg and for the second accepts string, ERROR: Object of class Illuminate\Http\JsonResponse could not be converted to int
  • Thank you Daan for the answer, I'm looking for cleaner code, can I transfer try...catch to checkExistence function? and just call checkExistence() in myFunc ?
  • And can I response json after Exception happens ?