How to check if a object has a static variable defined?

PHP: How to check if a object has a static variable defined?

If you have an object and you need to check if it has a const SOME_CONSTANT = 'foo' set, then you can use defined in the following way:

  1.         class ExampleClass {
  2.             const CONST_THAT_DOES_EXIST = 9;
  3.  
  4.             function does_it_have_const() {
  5.             // late static binding:
  6.                 var_dump( defined('static::CONST_THAT_DOES_EXIST') );
  7.                 var_dump( defined('static::CONST_THAT_DOES_NOT_EXIST') );
  8.  
  9.                 // or use self
  10.                 var_dump( defined('self::CONST_THAT_DOES_EXIST') );
  11.             }
  12.  
  13.         }

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to check if a object has a static variable defined?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to select all rows for a certain month (or day, year or time), using Eloquent

What is camel case?

How to find the average value of items in a Laravel Collection?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to hide certain file types from directory listings

What is the spaceship operator (<=>) in PHP?

What is Agile software development?

How to sort an array in javascript?

How to check if two strings are anagrams in PHP?

How to order a Laravel hasMany relationship?