How to define constant in class constructor?

2019-04-25 06:40发布

Can I define a class constant inside the class constructor function ?

(based on certain conditions)

3条回答
beautiful°
3楼-- · 2019-04-25 07:32

That goes against the idea of class constants - they should not be dependent on a specific instance. You should use a variable instead.

However, if you insist on doing this, are very adventurous and can install PHP extensions, you can have a look at the runkit extension that allows to modify classes and their constants at runtime. See this doc: http://www.php.net/manual/en/function.runkit-constant-add.php

查看更多
Summer. ? 凉城
4楼-- · 2019-04-25 07:41

I don't think you can.

It wouldn't make sense, either - a class constant can be used in a static context, where there is no constructor in the first place.

You'll have to use a variable instead - that's what they're there for.

查看更多
登录 后发表回答