I've a question about function declaration. I would like have something like:
password_hash('er', PASSWORD_ARGON2I);
https://www.php.net/manual/en/function.password-hash.php
When I create a function, I would like declare some possibilities like:
PASSWORD_DEFAULT = 1
PASSWORD_BCRYPT = 2
PASSWORD_ARGON2I = 3
PASSWORD_ARGON2ID = 4
Then, when the user use the function he just set the value of the constant or the constant.
Actually I do:
$instanceOfMyClass->myFunction('er', MyClass::A_CONSTANT);
It done the job, but I'm forced to write the class name before use the constant name. Then if I do thaht I've access to all the constant of the class.
I think, I talk about something like constants at the function level.
Thanks a lot :-)
PS: Is there a way to do a DeclarationType like int|object|string for a function attribute ? Actually I don't type hint in this case, and for object, I need to specify a class or an Interface, sometimes, I accept many object to call the __toString() magic class, then I accept all objects.
I don't really understand your issue
constants like PASSWORD_DEFAULT, but just it (no function name with double :).
but my guess is, you are looking for define().
I suggest you to utilize OOP as much as possible and so like others said, use class constants. But if you want global constants for whatever reason, it goes like this:
define('DIRECTION_FORWARD', 0);
define('DIRECTION_LEFT', 1);
define('DIRECTION_RIGHT', 2);
function goInDirection($direction = DIRECTION_FORWARD)
{
// ....
}
Instead of just sequential numbers as values, you can use bitmasks, which work with bitwise operators and the power of 2.
https://www.php.net/manual/en/language.operators.bitwise.php
There are many ways of doing it.
the defined constants can not be modified, but they can be analyzed and verified if a condition is met; although this one is doing all that; since it would be double work for something immutable / immutable
<?php
class Main{
const CONSTANT = 'value constant';
function ouputConts() {
echo var_dump(self::CONSTANT);
}
}
in your case; that I can keep in a constant:
<?php
class Main{
const CONSTANT1 = 1; //integer
const CONSTANT2 = 0.1345; //float
const CONSTANT3 = 'text'; //string
const CONSTANT4 = array(1,2,3,4,5,10,20); //array
const CONSTANT5 = true; //bollean
function ouputConts() {
echo var_dump(self::CONSTANT1);
echo var_dump(self::CONSTANT2);
echo var_dump(self::CONSTANT3);
echo var_dump(self::CONSTANT4);
echo var_dump(self::CONSTANT5);
}
}
because in php an object or any type of object is considered mutable; you can not declare constants of type objects.
Documentation:
https://php.net/manual/en/language.constants.syntax.php
https://www.php.net/manual/en/language.oop5.constants.php
So your other question is whether you can pass a constant as a property of a function:
Yes, but you should have some considerations:
If you are in the same class it is not necessary you can use the value in any function of the same class, without needing to pass it is Global for the class / Scope:
class Main{
const CONSTANT = 'value constant';
function function1() {
$this->function2();
}
function function2() {
$this->function3();
}
function function3() {
$this->function4();
}
function function4() {
echo var_dump(self::CONSTANT);
}
}
If the function belongs to another class I recommend you first store it in a variable ...:
class Main1{
const CONSTANT = 'value constant';
function function1() {
$foo = CONSTANT;
Main2::FunctionTest($foo);
}
}
class Main2{
function FunctionTest($foo = '') {
echo var_dump($foo);
}
}
// I can not verify it.
I hope I have helped you in your question; if you need more help or deepen your query leave me a comment.
Update; i see this commnet:
#ChristophBurschka By doing that, when you use the function you don't
have help for retrieve specific constant (all class consant are not
available for this function). When you use native PHP function, you
just have possibilities to use available constant and the IDE have the
capatibilities to find them (and it list it to you automatically when
you start to fill the corresponding argument)? Thanks for your answer
about Type hint :-)
if the problem is around the scope of your const:
You can declare global constants in your applications (out of all classes and functions):
<?php
if (!defined('DB_PASS')) {
define('DB_PASS', 'yourpassword');
}
It will be available in any class and function of the whole application. and its use is not to be feared, since they are IMMUTABLE CONSTANTS.
Update recovery and implementation
With the last way I explain, you can then make a comparison and define which data you want to use; if the data of the constant or the data sent by the user; but all this must be tied to an analysis of the user's data in a specific function that you define.
Last Update
With the new define you can this:
<?php
//declaration:
if (!defined('PASS_SIS')) {
define('PASS_SIS', array(
'PASSWORD_DEFAULT' => 1,
'PASSWORD_BCRYPT' => 2,
'PASSWORD_ARGON2I' => 3,
'PASSWORD_ARGON2ID' => 4,
));
}
//call Function
$instanceOfMyClass->myFunction('er');
//function
function myFunction('er'){
echo var_dump(PASS_SIS);
//Access to data:
echo PASS_SIS['PASSWORD_DEFAULT'];
}
Related
Assume this class code:
class Foo {
function method() {
echo 'works';
}
}
Is there any way to store a reference to the method method of a Foo instance?
I'm just experimenting and fiddling around, my goal is checking whether PHP allows to call $FooInstance->method() without writing $FooInstance-> every time. I know I could write a function wrapper for this, but I'm more interested in getting a reference to the instance method.
For example, this pseudo-code would theoretically store $foo->method in the $method variable:
$foo = new Foo();
$method = $foo->method; //Undefined property: Foo::$method
$method();
Apparently, as method is a method and I'm not calling it with () the interpreter thinks I'm looking for a property thus this doesn't work.
I've read through Returning References but the examples only show how to return references to variables, not methods.
Therefore, I've adapted my code to store an anonymous function in a variable and return it:
class Foo {
function &method() {
$fn = function() {
echo 'works';
};
return $fn;
}
}
$foo = new Foo();
$method = &$foo->method();
$method();
This works, but is rather ugly. Also, there's no neat way to call it a single time, as this seems to require storing the returned function in a variable prior to calling it: $foo->method()(); and ($foo->method())(); are syntax errors.
Also, I've tried returning the anonymous function directly without storing it in a variable, but then I get the following notice:
Notice: Only variable references should be returned by reference
Does this mean that returning/storing a reference to a class instance method is impossible/discouraged or am I overlooking something?
Update: I don't mind adding a getter if necessary, the goal is just getting a reference to the method. I've even tried:
class Foo {
var $fn = function() {
echo 'works';
};
function &method() {
return $this->fn;
}
}
But from the unexpected 'function' (T_FUNCTION) error I'd believe that PHP wisely doesn't allow properties to store functions.
I'm starting to believe that my goal isn't easily achievable without the use of ugly hacks as eval().
It is. You have to use an array, with two values: the class instance (or string of the class name if you are calling a static method) and the method name as a string. This is documented on the Callbacks Man page:
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
Demo (Codepad):
<?php
class Something {
public function abc() {
echo 'called';
}
}
$some = new Something;
$meth = array($some, 'abc');
$meth(); // 'called'
Note this is also works with the built-ins that require callbacks (Codepad):
class Filter {
public function doFilter($value) {
return $value !== 3;
}
}
$filter = new Filter;
$test = array(1,2,3,4,5);
var_dump(array_filter($test, array($filter, 'doFilter'))); // 'array(1,2,4,5)'
And for static methods -- note the 'Filter' instead of an instance of a class as the first element in the array (Codepad):
class Filter {
public static function doFilter($value) {
return $value !== 3;
}
}
$test = array(1,2,3,4,5);
var_dump(array_filter($test, array('Filter', 'doFilter'))); // 'array(1,2,4,5)'
// -------- or -----------
var_dump(array_filter($test, 'Filter::doFilter')); // As of PHP 5.2.3
Yes, you can. PHP has a "callable" pseudo-type, which is, in fact, either just a string or an array. Several functions (usort comes to mind) accept a parameter of the "callback" type: in fact, they just want a function name, or an object-method pair.
That's right, strings are callable:
$fn = "strlen";
$fn("string"); // returns 6
As mentioned, it's possible to use an array as a callback, too. In that case, the first element has to be an object, and the second argument must be a method name:
$obj = new Foo();
$fn = array($obj, "method");
$fn(); // calls $obj->method()
Previously, you had to use call_user_func to call them, but syntax sugar in recent versions make it possible to perform the call straight on variables.
You can read more on the "callable" documentation page.
No, as far as I know it's not possible to store a reference to a method in PHP. Storing object / class name and a method name in an array works, but it's just an array without any special meaning. You can play with the array as you please, for example:
$ref = [new My_Class(), "x"];
// all is fine here ...
$ref();
// but this also valid, now the 'reference' points to My_Other_Class::x()
// do you expect real reference to behave like this?
$ref[0] = new My_Other_Class();
$ref();
// this is also valid syntax, but it throws fatal error
$ref[0] = 1;
$ref();
// let's assume My_Class::y() is a protected method, this won't work outside My_Class
$ref = [new My_Class(), 'y'];
$ref();
this is prone to error as you loose syntax checking due to storing the method name as string.
you can't pass reliably a reference to a private or a protected method this way (unless you call the reference from a context that already has proper access to the method).
Personally I prefer to use lambdas:
$ref = function() use($my_object) { $my_object->x(); }
If you do this from inside $my_object it gets less clunky thanks to access to $this:
$ref = function() { $this->x(); }
this works with protected / private methods
syntax checking works in IDE (less bugs)
unfortunately it's less concise
class Foo
{
public $var ;
function __construct($value)
{
$this->var = $value ;
}
}
$myFoo = new Foo('hello');
echo $myFoo->var . '<br>' ; // output : hello
// Question : how can I prevent another programer from accidentaly doing the following
$myFoo = 4 ;
echo $myFoo ; // output : 4
my question is in the comment // Question :...
I would like my coworkers being able to assign values to $myFoo use only $myFoo->var (or whatever public mutators are available in the class Foo)
thank you
EDIT :
with all respect to the users who claim it is not possible, SPL_Types PECL extention was able to achieve that (to a certain degree) see e.g http://php.net/manual/en/class.splint.php or http://blog.felixdv.com/2008/01/09/spl_types-in-php-and-strong-typing/
You cannot do this in any weakly typed language. If you have functions that take this variable as an argument, you can use type hinting in PHP, but otherwise you cannot prevent people from re-assigning their variables.
This is true to an extent even for strongly typed languages. If a programmer creates two instances of a class, there is no mechanism to prevent them from assigning a different instance to a variable of the same type.
The only way this can happen is if the programmer explicitly uses constants instead of variables (such as using things like final in Java, or val in Scala, etc), but, either way, you have no control over it in any language.
You cannot prevent changing the type within the class, but if you make it protected or private and then add a setVariable() method (where Variable is your variable name) you can control the input. Something like:
class myClass {
protected $integer = 0;
public function setInteger($new_value)
{
if (!is_int($new_value)) {
throw new RuntimeException('Cannot assign non-integer value to myClass::$integer');
}
$this->integer = $new_value;
}
public function getInteger()
{
return $this->integer;
}
}
// Now, outside of the class, the $integer property can only be changed using setInteger()
$class = new myClass;
$class->setInteger('dog'); // Uncaught Runtime exception ...
$class->setInteger(5);
echo $class->getInteger(); // 5
An alternative version of that function would accept string numbers and convert them to integers:
public function setInteger($new_value)
{
if (!is_numeric($new_value)) {
throw new RuntimeException('Cannot assign non-integer value to myClass::$integer');
}
$this->integer = (int) $new_value;
}
$class->setInteger('5'); // 5
I'm learned php as functional and procedure language. Right now try to start learn objective-oriented and got an important question.
I have code:
class car {
function set_car($model) {
$this->model = $model;
}
function check_model()
{
if($this->model == "Mercedes") echo "Good car";
}
}
$mycar = new car;
$mycar->set_car("Mercedes");
echo $mycar->check_model();
Why it does work without declaration of $model?
var $model; in the begin?
Because in php works "auto-declaration" for any variables?
I'm stuck
Every object in PHP can get members w/o declaring them:
$mycar = new car;
$mycar->model = "Mercedes";
echo $mycar->check_model(); # Good car
That's PHP's default behaviour. Those are public. See manual.
Yes, if it doesn't exist, PHP declares it on the fly for you.
It is more elegant to define it anyway, and when working with extends it's recommended, because you can get weird situations if your extends are gonna use the same varnames and also don't define it private, protected or public.
More info:
http://www.php.net/manual/en/language.oop5.visibility.php
PHP class members can be created at any time. In this way it will be treated as public variable. To declare a private variable you need to declare it.
Yes. But this way variables will be public. And declaration class variable as "var" is deprecated - use public, protected or private.
No, it's because $model is an argument of the function set_car. Arguments are not exactly variables, but placeholders (references) to the variables or values that will be set when calling the function (or class method). E.g., $model takes the value "Mercedes" when calling set_car.
I think this behavior can lead to errors.
Lets consider this code with one misprint
declare(strict_types=1);
class A
{
public float $sum;
public function calcSum(float $a, float $b): float
{
$this->sum = $a;
$this->sums = $a + $b; //misprinted sums instead of sum
return $this->sum;
}
}
echo (new A())->calcSum(1, 1); //prints 1
Even I use PHP 7.4+ type hints and so one, neither compiler, nor IDE with code checkers can't find this typo.
I have a string containing the class name and I wish to get a constant and call a (static) method from that class.
<?php
$myclass = 'b'; // My class I wish to use
$x = new x($myclass); // Create an instance of x
$response = $x->runMethod(); // Call "runMethod" which calls my desired method
// This is my class I use to access the other classes
class x {
private $myclass = NULL;
public function __construct ( $myclass ) {
if(is_string($myclass)) {
// Assuming the input has a valid class name
$this->myclass = $myclass;
}
}
public function runMethod() {
// Get the selected constant here
print $this->myclass::CONSTANT;
// Call the selected method here
return $this->myclass::method('input string');
}
}
// These are my class(es) I want to access
abstract class a {
const CONSTANT = 'this is my constant';
public static function method ( $str ) {
return $str;
}
}
class b extends a {
const CONSTANT = 'this is my new constant';
public static function method ( $str ) {
return 'this is my method, and this is my string: '. $str;
}
}
?>
As I expected (more or less), using $variable::CONSTANT or $variable::method(); doesn't work.
Before asking what I have tried; I've tried so many things I basically forgot.
What's the best approach to do this? Thanks in advance.
To access the constant, use constant():
constant( $this->myClass.'::CONSTANT' );
Be advised: If you are working with namespaces, you need to specifically add your namespace to the string even if you call constant() from the same namespace!
For the call, you'll have to use call_user_func():
call_user_func( array( $this->myclass, 'method' ) );
However: this is all not very efficient, so you might want to take another look at your object hierarchy design. There might be a better way to achieve the desired result, using inheritance etc.
in php 7 you can use this code
echo 'my class name'::$b;
or
#Uncomment this lines if you're the input($className and $constName) is safe.
$reg = '/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/';
if(preg_match($reg,$className) !== 1 || preg_match($reg,$constName) !== 1)
throw new \Exception('Oh, is it an attack?');
$value = eval("return $className::$constName;");
You can achieve it by setting a temporary variable. Not the most elegant way but it works.
public function runMethod() {
// Temporary variable
$myclass = $this->myclass;
// Get the selected constant here
print $myclass::CONSTANT;
// Call the selected method here
return $myclass::method('input string');
}
I guess it's to do with the ambiguity of the ::, at least that what the error message is hinting at (PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM)
Use call_user_func to call static method:
call_user_func(array($className, $methodName), $parameter);
Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.
Refer to http://php.net/manual/en/language.oop5.abstract.php
This might just be tangential to the subject but, while searching for my own issue I found that the accepted answer pointed me in the right direction, so I wanted to share my problem & solution in case someone else might be stuck in a similar fashion.
I was using the PDO class and was building some error options from an ini config file. I needed them in an associative array in the form: PDO::OPTION_KEY => PDO::OPTION_VALUE, but it was of course failing because I was trying to build the array with just PDO::$key => PDO::$value.
The solution (inspired from the accepted answer):
$config['options'] += [constant('PDO::'.$key) => constant('PDO::'.$option)];
where everything works if you concatenate the class name and the Scope Resolution Operator as a string with the variable and get the constant value of the resulting string through the constant function (more here).
Thank you and I hope this helps someone else!
I've come across some unexpected behavior with static variables defined inside object methods being shared across instances. This is probably known behavior, but as I browse the PHP documentation I can't find instances of statically-defined variables within object methods.
Here is a reduction of the behavior I've come across:
<?php
class Foo {
public function dofoo() {
static $i = 0;
echo $i++ . '<br>';
}
}
$f = new Foo;
$g = new Foo;
$f->dofoo(); // expected 0, got 0
$f->dofoo(); // expected 1, got 1
$f->dofoo(); // expected 2, got 2
$g->dofoo(); // expected 0, got 3
$g->dofoo(); // expected 1, got 4
$g->dofoo(); // expected 2, got 5
Now, I would have expected $i to be static per instance, but in reality $i is shared between the instances. For my own edification, could someone elaborate on why this is the case, and where it's documented on php.net?
This is the very definition of static.
If you want members to be specific to an instance of an object, then you use class properties
e.g.
<?php
class Foo
{
protected $_count = 0;
public function doFoo()
{
echo $this->_count++, '<br>';
}
}
Edit: Ok, I linked the documentation to the OOP static properties. The concept is the same though. If you read the variable scope docs you'll see:
Note: Static declarations are resolved in compile-time.
Thus when your script is compiled (before it executes) the static is "setup" (not sure what term to use). No matter how many objects you instantiate, when that function is "built" the static variable references the same copy as everyone else.
I agree that the current PHP documentation is not sufficiently clear on exactly what "scope" means for a static variable inside a non-static method.
It is of course true (as hobodave indicates) that "static" generally means "per class", but static class properties are not exactly the same thing as static variables within a (non static) method, in that the latter are "scoped" by method (every method in a class can have its own static $foo variable, but there can be at most one static class member named $foo).
And I would argue that although the PHP 5 behavior is consistent ("static" always means "one shared instance per class"), it is not the only way that PHP could behave.
For example, most people use static function variables to persist state across function calls, and for global functions the PHP behavior is exactly what most everyone would expect. So it is certainly possible to imagine a PHP interpreter that maintains the state of certain method variables across method invocation and does so "per instance", and that's actually what I also expected to happen the first time I declared a local method variable to be static.
That is what static is, it's the same variable across all instances of the class.
You want to write this so that the variable is a private member of the instance of the class.
class Foo {
private $i = 0;
public function dofoo() {
echo $this->i++ . '<br>';
}
}
The static keyword can be used with variables, or used with class methods and properties. Static variables were introduced in PHP 4 (I think, it might have been earlier). Static class members/methods were introduced in PHP 5.
So, per the manual, a static variable
Another important feature of variable scoping is the static
variable. A static variable exists only in a local function
scope, but it does not lose its value when program execution
leaves this scope.
This is consistant with the behavior you described. If you want a per instance variable, used a regular class member.
Ups 7 years it a long time but anyway here it goes.
All classes have a default constructor why am I saying this?!?
Because if you define a default behaviour in constructor each instance of the class will be affected.
Example:
namespace Statics;
class Foo
{
protected static $_count;
public function Bar()
{
return self::$_count++;
}
public function __construct()
{
self::$_count = 0;
}
}
Resulting in:
require 'Foo.php';
use Statics\Foo;
$bar = new Foo();
echo $bar->bar().'<br>';
echo $bar->bar().'<br>';
echo $bar->bar().'<br>';
$barcode = new Foo();
echo $barcode->bar().'<br>';
echo $barcode->bar().'<br>';
echo $barcode->bar().'<br>';
0
1
2
0
1
2
Every new instance from the upper class will start from 0!
The static count behaviour will NOT be shared across the multiple instances as it will be starting from the value assigned in constructor.
If you need to share data across multiple instances all you need to do is to define a static variable and assign default data outside the constructor!
Example:
namespace Statics;
class Foo
{
//default value
protected static $_count = 0;
public function Bar()
{
return self::$_count++;
}
public function __construct()
{
//do something else
}
}
Resulting in:
require 'Foo.php';
use Statics\Foo;
$bar = new Foo();
echo $bar->bar().'<br>';
echo $bar->bar().'<br>';
echo $bar->bar().'<br>';
$barcode = new Foo();
echo $barcode->bar().'<br>';
echo $barcode->bar().'<br>';
echo $barcode->bar().'<br>';
0
1
2
3
4
5
As you can see the results are completely different, the memory space allocation is the same in between class instances but it can produce different results based on how you define default value.
I hope it helped, not that the above answers are wrong but I felt that it was important to understand the all concept from this angle.
Regards, from Portugal!