Jump to content

Here we go again - Classes


maxudaskin

Recommended Posts

PHP.NET EXAMPLE

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        A::foo();
    }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

 

Please correct me if I am wrong, but is this how it goes?

 

The class "A" is assigned to the variable "a".

"$a->foo();" calls the function "foo" inside the class "A"

When the single arrow is used, "$this" (please complete this line)

"A::foo();" does not use "$this"

Link to comment
https://forums.phpfreaks.com/topic/117783-here-we-go-again-classes/
Share on other sites

Say you have $a= new A();   anywhere you see '$this' inside the class is the same as saying '$a' (pretty much).  So in that example, to call foo() outside the class you do $a->foo() while if you want to call the function from within the class, you use $this->foo().

 

Hope that's clear enough.

 

as for explaining A::foo() read this http://www.phpbuilder.com/manual/en/language.oop5.paamayim-nekudotayim.php

that's better than how I might try explaining it.

so $this refers to the variable that has it assigned to?

 

As unclear as that question is, I think I know what you mean, and yes. 

 

in the case $jim= new A();

say you do $jim->foo();  Now inside the class A, you see $this->bar();

'$this->bar()' would be calling bar(); for the instance '$jim' of class A.

 

I'll try this:

Say you have class Dog.  You have two dogs, 1 named jim, 1 named john.  Class Dog has a Scratch method.  To make John scratch himself and bark:

 

<?php
class Dog{
    public $name;
    public function __construct($name){
        $this->name=$name;
    }

    public function scratch(){
        echo $this->name.' scratches himself';
        $this->bark();
    }

    public function bark(){
        echo $this->name.' barks';
    }
}

$jim=new Dog('jim');
$john=new Dog('john');
$john=scratch();
?>
This would display:
John scratches himself.John barks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.