Reputation: 2275
I have a page with the following class:
class SimpleClass
{
public $var6 = myConstant;
public $var7 = array(true, false);
}
And I ran the page on browser. It throws no errors/warning/notice.
But then I created an object like:
$newvar = new SimpleClass;
echo $newvar->var6;
And it gives me "Notice: Use of undefined constant myConstant
".
I know myConstant needs to be defined to be accessed, which has not been.
My question is why am I getting this Notice message only after object creation and not before?
Upvotes: 0
Views: 63
Reputation: 9693
here when you are trying to retrieve the $var6, It is assuming it like public $var6 = 56; //any constant .
read about how to declare constant , if you want constant there. Or use quote , so that it will treat it as string.
string
<?php
class SimpleClass
{
public $var6 = 'myConstant';
public $var7 = array(true, false);
}
$newvar = new SimpleClass;
echo $newvar->var6;
constant
class MyClass
{
const CONSTANT = 'constant value';
}
echo MyClass::CONSTANT . "\n";
Upvotes: 0
Reputation: 13128
You're getting the error because you're instantiating the class in the second example.
$newvar = new SimpleClass();
This throws the error as it tries to "compile" it, thus trying to harness myConstant
within the global namespace, hence the error (as it isn't defined).
If you don't call the class, you wouldn't have the error throwing as it isn't in use.
Clarification on your comment here:
You only get the error message due to the fact that you instantiated the class. If you didn't do that, the error wouldn't show. This is correct practice and exactly how PHP functions.
Upvotes: 1