How to return null inside the function/method if a property in the class is not found?

Asked
Active3 hr before
Viewed126 times

9 Answers

methodreturnpropertyfunctioninside
90%

I wonder if I can make the function to return null if no property is found?,Use this magic method inside your class. Whenever an undefined property is requested, null is returned.,Decided to make that function above into a class, but still cannot get __get() working properly,, The shape and extension of the fundamental particles

Bringing John's answer about __get() together:

< ? //PHP 5.3+

class maybeBag {
   public
   function __get($name) {
      if (isset($this - > $name) === true) {
         return $this - > $name;
      } else {
         return null;
      }
   }

   public static
   function ensureIsObject($values) {
      if (\is_array($values) !== true) {
         return $values;
      }
      $o = new static(); //Late-bound make instance of own class
      foreach($values as $key => $value) {
         $o - > $key = static::ensureIsObject($value);
      }
      return $o;
   }
}

//Demo

$type = array(
   'category' => 'admin',
   'person' => 'unique'
);
$type = maybeBag::ensureIsObject($type);

var_dump($type - > category); //string(5) "admin"
var_dump($type - > image); //NULL

?
>
load more v
88%

Initializes a new instance of the NullReferenceException class with serialized data.,For a list of initial property values for an instance of NullReferenceException, see the NullReferenceException constructors.,Handling NullReferenceException in release code,The exception that is thrown when there is an attempt to dereference a null object reference.

You've forgotten to instantiate a reference type. In the following example, names is declared but never instantiated:

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main(string[] args)
   {
      int value = Int32.Parse(args[0]);
      List<String> names;
      if (value > 0)
         names = new List<String>();

      names.Add("Major Major Major");
   }
}
// Compilation displays a warning like the following:
//    Example1.cs(10) : warning BC42104: Variable //names// is used before it
//    has been assigned a value. A null reference exception could result
//    at runtime.
//
//          names.Add("Major Major Major")
//          ~~~~~
// The example displays output like the following output:
//    Unhandled Exception: System.NullReferenceException: Object reference
//    not set to an instance of an object.
//       at Example.Main()
Imports System.Collections.Generic

Module Example
Public Sub Main()
Dim names As List(Of String)
names.Add("Major Major Major")
End Sub
End Module
   ' Compilation displays a warning like the following:
'    Example1.vb(10) : warning BC42104: Variable '
names ' is used before it 
'    has been assigned a value. A null reference exception could result 
'    at runtime.
'    
'          names.Add("Major Major Major")
'          ~~~~~
' The example displays output like the following output:
'    Unhandled Exception: System.NullReferenceException: Object reference 
'    not set to an instance of an object.
'       at Example.Main()

Some compilers issue a warning when they compile this code. Others issue an error, and the compilation fails. To address this problem, instantiate the object so that its value is no longer null. The following example does this by calling a type's class constructor.

using System;
using System.Collections.Generic;

public class Example
{
   public static void Main()
   {
      List<String> names = new List<String>();
      names.Add("Major Major Major");
   }
}
Imports System.Collections.Generic

Module Example
Public Sub Main()
Dim names As New List(Of String)()
names.Add("Major Major Major")
End Sub
End Module
load more v
72%

If the method returns a collection type, then we can simply substitute an empty collection.,Both of these return an immutable list so the calling code should make no attempt to modify it.,This leads to ambiguity because we can't be certain what null actually means here.   We would need an additional check with the containsKey() method to be sure.,The Collections class has a static method for this purpose:

Blog blog = null;
long id = blog.getId(); // NullPointerException
load more v
65%

The map method of the Optional class does exactly the same: the value contained inside Optional is "transformed" by the function passed as an argument (here, a method reference to extract the USB port), while nothing happens if Optional is empty.,Notice that all this code does is extract one object from another one, which is exactly what the map method is for. Earlier in the article, we changed our model so a Computer has an Optional<Soundcard> and a Soundcard has an Optional<USB>, so we should be able to write the following:,There's a direct parallel to the map method used with streams. There, you pass a function to the map method, which applies this function to each element of a stream. However, nothing happens if the stream is empty.,The filter method takes a predicate as an argument. If a value is present in the Optional object and it matches the predicate, the filter method returns that value; otherwise, it returns an empty Optional object. You might have seen a similar pattern already if you have used the filter method with the Stream interface.

String version = "UNKNOWN";
if (computer != null) {
   Soundcard soundcard = computer.getSoundcard();
   if (soundcard != null) {
      USB usb = soundcard.getUSB();
      if (usb != null) {
         version = usb.getVersion();
      }
   }
}
load more v
75%

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public. , Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public. , As of PHP 7.1.0, class constants may be defined as public, private, or protected. Constants declared without any explicit visibility keyword are defined as public. , Class Constants

string(5)
"hello"
Accessed the private method.
40%

In a function with an explicit never return type annotation, all return statements (if any) must have expressions of type never and the end point of the function must not be reachable.,The type checker previously considered null and undefined assignable to anything. Effectively, null and undefined were valid values of every type and it wasn’t possible to specifically exclude them (and therefore not possible to detect erroneous use of them).,More on FunctionsHow to provide types to functions in JavaScript,In a function expression or arrow function with no return type annotation, if the function has no return statements, or only return statements with expressions of type never, and if the end point of the function is not reachable (as determined by control flow analysis), the inferred return type for the function is never.

Example
ts // Compiled with --strictNullCheckslet x: number;let y: number | undefined;let z: number | null | undefined;x = 1; // Oky = 1; // Okz = 1; // Okx = undefined; // Errory = undefined; // Okz = undefined; // Okx = null; // Errory = null; // Errorz = null; // Okx = y; // Errorx = z; // Errory = x; // Oky = z; // Errorz = x; // Okz = y; // Ok
load more v
22%

You will get undefined value when you call a non-existent property or method of an object. ,If you pass less arguments in function call then, that parameter will have undefined value. , You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value. , An undefined evaluates to false when used in conditional expression.

var myVar = null;

alert(myVar); // null 
load more v
60%

Dart is a “pure” object-oriented language in that all objects are instances of classes. But Dart does not require all code to be defined inside a class—you can define top-level variables, constants, and functions like you can in a procedural or functional language.,In idiomatic Dart, classes define kinds of objects. A type that is never instantiated is a code smell.,Exception: If returning null means something different from yielding an empty container, it might make sense to use a nullable type.,“Obvious” isn’t precisely defined, but these are all good candidates:

E for the element type in a collection:

class IterableBase<E> {}
class List<E> {}
class HashSet<E> {}
class RedBlackTree<E> {}
load more v
48%

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.,Document.getElementById(),Document reference for other methods and properties you can use to get references to elements in the document.,The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

var element = document.getElementById(id);
load more v

Other "method-return" queries related to "How to return null inside the function/method if a property in the class is not found?"