Asked  7 Months ago    Answers:  5   Viewed   36 times

I see the variable $this in PHP all the time and I have no idea what it's used for. I've never personally used it.

Can someone tell me how the variable $this works in PHP?

 Answers

95

It's a reference to the current object, it's most commonly used in object oriented code.

  • Reference: http://www.php.net/manual/en/language.oop5.basic.php
  • Primer: http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html

Example:

<?php
class Person {
    public $name;

    function __construct( $name ) {
        $this->name = $name;
    }
};

$jack = new Person('Jack');
echo $jack->name;

This stores the 'Jack' string as a property of the object created.

Tuesday, June 1, 2021
 
apokryfos
answered 7 Months ago
56

It's the modulus operator, as mentioned, which returns the remainder of a division operation.

Examples: 3%5 returns 3, as 3 divided by 5 is 0 with a remainder of 3.

5 % 10 returns 5, for the same reason, 10 goes into 5 zero times with a remainder of 5.

10 % 5 returns 0, as 10 divided by 5 goes exactly 2 times with no remainder.

In the example you posted, (3 - 2 + 7) works out to 8, giving you 8 % 7, so $number will be 1, which is the remainder of 8/7.

Wednesday, March 31, 2021
 
rasmusx
answered 9 Months ago
43

You could do it this way, but it could be improved. Having the actual validators capsule their own validation logic is good. Extending them from a base class isn't. Let's implement an interface instead. This way, any class can be a Validator.

interface IValidate
{
    public function validate($value);
}

Your validators would look like this then:

class IsNumeric implements IValidate
{
    public function validate($value)
    {
        return is_numeric($value);
    }
}

and

class GreaterThan implements IValidate
{
    protected $_value;
    public function __construct($value)
    {
        $this->_value = $value;
    }
    public function validate($value)
    {
        return $value > $this->_value;
    }
}

You'd still have a main Validator class. Unlike in your example, the Validator below accepts multiple Validators, which will allow you to create a Filter Chain.

class Validator implements IValidate
{
    protected $_validators;

    public function addValidator(IValidate $validator)
    {
        $this->_validators[] = $validator;
        return $this;
    }
    public function validate($value)
    {
        foreach($this->_validators as $validator) {
            if ($validator->validate($value) === FALSE) {
                return FALSE;
            }
        }
        return TRUE;
    }
}

And this could be used like:

$validator = new Validator;
$validator->addValidator(new IsNumeric)
          ->addValidator(new GreaterThan(5));

var_dump( $validator->validate('ten') ); // FALSE
var_dump( $validator->validate('10') );  // TRUE
var_dump( $validator->validate('1') );   // FALSE

The above is pretty much a Command pattern. And due to the Validator implementing IValidate as well, it is also a Composite. You could take the Validator chain from above and stack it into another Validator Chain, e.g.

$numericGreaterThanFive = new Validator;
$numericGreaterThanFive->addValidator(new IsNumeric)
                       ->addValidator(new GreaterThan(5));

$otherValidator = new Validator;
$otherValidator->addValidator(new Foo)
               ->addValidator(new Bar)
               ->addValidator($numericGreatherThanFive);

For convenience, you could add a static factory method for creating Validators with the actual Validation Command objects (as shown elsewhere).

On a sidenote: the Zend Framework already has an extensive number of Validators you can build on. Since ZF is a component library, you can use them without having to migrate your entire application to ZF.

Wednesday, March 31, 2021
 
waylaidwanderer
answered 9 Months ago
69

I'm going to begin this answer with an illustration:

var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
    // this is a reference to the element clicked on

    var that = this;

    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});

My answer originally demonstrated this with jQuery, which is only very slightly different:

$('#element').click(function(){
    // this is a reference to the element clicked on

    var that = this;

    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});

Because this frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this.

Personally, I dislike the use of that as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl.

Tuesday, June 1, 2021
 
braindamage
answered 7 Months ago
59

Yes, it is possible, that is know as variable functions, have a look at this.

Example from PHP's official site:

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

In your case, make sure that the function do_the_thing exists. Also note that you are storing the return value of the function:

$req = $class->$function_name();

Try to see what the variable $req contains. For example this should give you info:

print_r($req); // or simple echo as per return value of your function

Note:

Variable functions won't work with language constructs such as echo(), print(), unset(), isset(), empty(), include(), require() and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

Friday, September 24, 2021
 
Good Person
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share