Arvind Singhal
Arvind Singhal

Reputation: 3

Sorting an array using oop

The following is a sample array:

array(11, -2, 4, 35, 0, 8, -9)

I would like to use oop to sort it and generate this result:

Output :

Array ( [0] => -9 [1] => -2 [2] => 0 [3] => 4 [4] => 8 [5] => 11 [6] => 35 ) 

I was provided the solution far below, which works. What I don't understand is what the __construct is doing. I have a beginner's understanding of how constructors work, but what specifically is the purpose of this constructor?:

 public function __construct(array $asort)  
 {  
    $this->_asort = $asort;  

Is it turning the input into an array?

<?php  
class array_sort  
{  
    protected $_asort;  

    public function __construct(array $asort)  
     {  
        $this->_asort = $asort;  
     }  
    public function alhsort()  
     {  
        $sorted = $this->_asort;  
        sort($sorted);  
        return $sorted;  
      }  
}  
$sortarray = new array_sort(array(11, -2, 4, 35, 0, 8, -9));  
print_r($sortarray->alhsort());  
?>  

Upvotes: 0

Views: 1245

Answers (4)

ABHISHEK GUPTA
ABHISHEK GUPTA

Reputation: 71

<?php  
class array_sort  
{   
    public $temp;
    public function alhsort(array $sorted)  
     {  
        for($i=0; $i<count($sorted)-1; $i++){
            for($j=$i+1; $j<count($sorted); $j++){
                if($sorted[$i] > $sorted[$j]){
                    $temp =  $sorted[$i];
                    $sorted[$i] = $sorted[$j];
                    $sorted[$j] = $temp;
                }
            }
        } 
        return $sorted;  
      }  
}  
$sortarray = new array_sort();  
print_r($sortarray->alhsort(array(11, -2, 4, 35, 0, 8, -9)));  
?> 

Upvotes: 0

Linus Nelson
Linus Nelson

Reputation: 36

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

Here is a reference and a longer primer.

The array $asort is assigned to the variable $_asort of the class and take $_asort as a property of the object created.

Upvotes: 1

LMS94
LMS94

Reputation: 1036

This is way too over engineered!

Why do you want to do this oop when you can simply call

$sortarray = sort(array(11, -2, 4, 35, 0, 8, -9));

To answer your question, __construct() is called whenever the object is instantiated new array_sort(array(11, -2)); instantiates the array_sort object.

Your particular constructor is setting the protected property $_asort with the value passed into the first argument $asort.

Upvotes: 0

scottevans93
scottevans93

Reputation: 1079

The __construct() is initialising the protected $_asort;. Essentially moving your array parameter into a class variable, which is then utilised by alhsort().

For clarification, the Input as you said is already an array once you declare array(...) the construct simple copies it into a variable accessible by the entire array_sort class.

Upvotes: 0

Related Questions