What is the DS\Vector copy() method in PHP?
The copy() method of the DS\Vector class in PHP creates and returns a shallow copy of a provided vector.
The process is illustrated below:
The prototype of the copy() method is shown below:
Ds\Vector public Ds\Vector::copy( void )
Parameters
The copy() method does not accept any parameters.
Return value
The copy() method returns a shallow copy of the vector used to invoke the method.
Example
The code below shows how the copy() method works in PHP:
<?php// initialize vector$sourceVector = new \Ds\Vector([1, 2, 3]);// create shallow copy$copyVector = $sourceVector->copy();// print vectorsprint_r($sourceVector);print_r($copyVector);// add element to shallow copy$copyVector->push(4);print("\nAfter item addition to copyVector:\n\n");print_r($sourceVector);print_r($copyVector);// add element to original vector$sourceVector->push(5);print("\nAfter item addition to sourceVector:\n\n");print_r($sourceVector);print_r($copyVector);?>
The above code produces the following output:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
)
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
)
After item addition to copyVector:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
)
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
After item addition to sourceVector:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
)
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Note: To run this program, you need to install Data Structures for PHP on your local machine.
Explanation
First, a vector that holds integer values is initialized. The copy() method in line creates a shallow copy of the original vector.
The code proceeds to add a value to the newly created copyVector. Since copyVector is a copy of sourceVector, the changes made to copyVector are not reflected in the original vector.
Similarly, when a value is added to sourceVector, the changes are not reflected in copyVector.
Free Resources